Threading and Conditions

Ken Seehof kens at sightreader.com
Wed Mar 22 21:44:54 CET 2000


Gordon McMillan wrote:

> Ken Seehof wrote:
>
> . . .
> > Unfortunately, the documentation is inadequate.  Does anyone know of a
> > whole sample program using conditions?
>
> The test code at the bottom of the module.

That's the inadequate documentation I was talking about.  This "example"would
be much better if it showed the whole interaction, including creating the
threads and conditions.  An example should be a working script that
demonstrates a feature. Anyway, I did manage to get it to work.

Here's the "example":

     # Consume one item
     cv.acquire()
     while not an_item_is_available():
         cv.wait()
     get_an_available_item()
     cv.release()

     # Produce one item
     cv.acquire()
     make_an_item_available()
     cv.notify()
     cv.release()


Anyway I did manage to finally get it to work.
Here's my code based on the "example" (something like this belongs in the
documentation):

from threading import *
from time import sleep
import sys

def an_item_is_available():
    return (item != None)

def make_an_item_available():
    global item, done
    if len(x)>0:
        item = x[0]
        del x[0]
    else:
        item = 'end'
        done = 1

def get_an_available_item():
    global item
    print item
    item = None

def server():
    print 'starting server'
    sys.stdout.flush()
    while item!='end':
        for i in range(1000):
            sleep(0.001)

        # Produce one item
        cv.acquire()
        make_an_item_available()
        cv.notify()
        cv.release()

def client():
    print 'starting client'
    sys.stdout.flush()
    while not done:
        while not an_item_is_available():
            # Consume one item
            cv.acquire()
            cv.wait()
            get_an_available_item()
            cv.release()

def test():
    global cv, td, x, item, done
    x = ['alpha', 'beta', 'gamma', 'delta']
    item = None
    done = 0

    td = Thread(target = server)
    td.setDaemon(1)
    cv = Condition()
    td.start()
    client()



> > Is the Threading module the right thing to use for multi-threading?
>
> Yes.
>
> - Gordon







More information about the Python-list mailing list