Aug-01-2017, 10:14 PM
A minimal example with a class without any queues, using locks instead.
With queues is a better approach, but I'm to tired to wrap my mind around queues.
With queues is a better approach, but I'm to tired to wrap my mind around queues.
import time import threading class Foo: def __init__(self, on_duration, off_duration): self._on_duration = on_duration self._off_duration = off_duration self.lock = threading.Lock() @property def off_duration(self): return self._off_duration @off_duration.setter def off_duration(self, value): with self.lock: # BLOCKING # in this block no other thread # is allowed to aquire the lock self._off_duration = value @property def on_duration(self): return self._on_duration @on_duration.setter def on_duration(self, value): with self.lock: # BLOCKING self._on_duration = value # in this block no other thread # is allowed to aquire the lock def start(self): thread = threading.Thread(target=self.run) thread.setDaemon(True) thread.start() def run(self): while True: with self.lock: # BLOCKING # here we assign the two values from # self.on_duration and self.off_duration # during this time, the other lock will # block, also the other assigments, which # are realized with @porperty.setter # will block this lock here. # this will prevent race conditions on_duration = self.on_duration off_duration = self.off_duration # during this time all other locks with # using the same lock object have to wait # a assigment is very short, so this # will not affect your gui # outside the lock block # here we use the new variables, we have # assigned before # no blocking here # and the sleep function won't block # because it's outside of the lock print('On', on_duration) time.sleep(on_duration) print('Off', off_duration) time.sleep(on_duration) foo = Foo(5, 5) foo.start() time.sleep(10) foo.on_duration = 2 foo.off_duration = 2 time.sleep(10) # program ends here, main thread is killd # because there are no non-daemon threads left
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!