Threading question

Trent Mick trentm at ActiveState.com
Wed Jun 19 20:35:42 EDT 2002


[David LeBlanc wrote]
> with a thread sitting in a loop processing intermittant transactions from a
> buffer, how does one wait if reading an empty buffer does not block - how do
> you relinquish control to other threads/processes?

There are probably a bunch of ways to do it but here is one.

If you have access to the code that populates the buffer then given
everyone a handle to a condition variable and have the reader .wait() on
that condition and have anyone who adds data to the buffer .notify() or
.notifyAll() on that condition.


import threading
class Reader(threading.Thread):
    def __init__(self, cond):
        self.cond = cond
    def run(self):
        self.cond.acquire()
        self.cond.wait()
        self.cond.release()

        # Get some data from the buffer and process it...
        # (Note that you'll probably want to lock the buffer when
        # modifying it here.)


class Writer(thrading.Thread):
    def __init__(self, cond):
        self.cond = cond
    def run(self):
        # Add some data to the buffer...
        # (Note that you'll probably want to lock the buffer when
        # modifying it here.)

        self.cond.acquire()
        self.cond.notify()  # or .notifyAll()
        self.cond.release()


Trent
        

-- 
Trent Mick
TrentM at ActiveState.com





More information about the Python-list mailing list