changing params in while loop

Ben Cartwright bencvt at gmail.com
Tue Feb 28 01:32:40 EST 2006


robin wrote:
> i have this function inside a while-loop, which i'd like to loop
> forever, but i'm not sure about how to change the parameters of my
> function once it is running.
> what is the best way to do that? do i have to use threading or is there
> some simpler way?


Why not just do this inside the function?  What exactly are you trying
to accomplish here?  Threading could work here, but like regexes,
threads are not only tricky to get right but also tricky to know when
to use in the first place.

That being said, here's some example threading code to get you started
(PrinterThread.run is your function; the ThreadSafeStorage instance
holds your parameters):

import threading
import time

class ThreadSafeStorage(object):
    def __init__(self):
        object.__setattr__(self, '_lock', threading.RLock())
    def acquirelock(self):
        object.__getattribute__(self, '_lock').acquire()
    def releaselock(self):
        object.__getattribute__(self, '_lock').release()
    def __getattribute__(self, attr):
        if attr in ('acquirelock', 'releaselock'):
            return object.__getattribute__(self, attr)
        self.acquirelock()
        value = object.__getattribute__(self, attr)
        self.releaselock()
        return value
    def __setattr__(self, attr, value):
        self.acquirelock()
        object.__setattr__(self, attr, value)
        self.releaselock()

class PrinterThread(threading.Thread):
    """Prints the data in shared storage once per second."""
    storage = None
    def run(self):
        while not self.storage.killprinter:
            self.storage.acquirelock()
            print 'message:', self.storage.message
            print 'ticks:', self.storage.ticks
            self.storage.ticks += 1
            self.storage.releaselock()
            time.sleep(1)

data = ThreadSafeStorage()
data.killprinter = False
data.message = 'hello world'
data.ticks = 0
thread = PrinterThread()
thread.storage = data
thread.start()
# do some stuff in the main thread
time.sleep(3)
data.acquirelock()
data.message = 'modified ticks'
data.ticks = 100
data.releaselock()
time.sleep(3)
data.message = 'goodbye world'
time.sleep(1)
# notify printer thread that it needs to die
data.killprinter = True
thread.join()

# output:
"""
message: hello world
ticks: 0
message: hello world
ticks: 1
message: hello world
ticks: 2
message: modified ticks
ticks: 100
message: modified ticks
ticks: 101
message: modified ticks
ticks: 102
message: goodbye world
ticks: 103
"""

--Ben




More information about the Python-list mailing list