threading question

Ben Wolfson rumjuggler at cryptarchy.org
Sat May 13 20:40:11 CEST 2000


I'm a complete novice as to threads, but the recent Waiter/Messenger
examples made them seem simpler than the docs indicated, so I'm trying
to figure them out.

This script was basically so I could mess around with Conditions, but
it never exits.

from threading import *
from time import sleep

def printlist(list, cond):
    cond.acquire()
    while list:#this loop ends first in thread '1'
        print 'printing in %s' % currentThread().getName()
        i, list = list[0], list[1:]
        print i
        sleep(1)
        cond.notify()
        cond.wait()#when thread '1' breaks out of the loop, the 
                   #thread '2' is here
        cond.acquire()
    cond.notify() #so this should wake thread '2'
    cond.release()#and this should allow it to acquire the condition
                  #allowing it to break out of the loop.  When it
                  #calls notify(), nothing should happen, and then
                  #it should release.  Instead, thread '2' never
                  #acquires the condition in the first place
                  #once thread '1' reaches this point.
    
def makenew():
    cond = Condition()
    cond.acquire()
    t = Thread(target=printlist,name='2',args=(['la','di','da'],cond))
    t.start()
    printlist([1, 2, 3], cond)

th = Thread(target=makenew,name='1')
th.start()

---output:
printing in 1
1
printing in 2
la
printing in 1
2
printing in 2
di
printing in 1
3
printing in 2
da


Setting thread '2' to be daemonic allows the script to exit, but I'd
like to know what the problem was.

-- 
Barnabas T. Rumjuggler

"It's is not, it isn't ain't, and it's it's, not its, if you mean it
is. If you don't, it's its. Then too, it's hers. It isn't her's. It
isn't our's either. It's ours, and likewise yours and theirs."
   -- Oxford University Press, Edpress News



More information about the Python-list mailing list