[Tutor] Threads threads threads gaaahgh (foaming at the mouth)
Hanna Joo
hanna@chagford.com
Wed, 13 Jun 2001 12:26:26 -0700
Big thanks to those who helped me. This is the updated version of the
producer consumer thing.
The problem now is getting 'notify' and 'wait' working. The reference book
says that I those are the methods of condition variables (boohoohoo english
is not even my first language and people do this to me). I went through
chapters on threads again, but I still don't really get it. help please
T_____T (tears streaming down).
TIA
import threading
from random import randint
class Soup:
def __init__(self):
self.next = 0
self.isFull = 0
self.isEmpty = 1
self.buff = ""
def eat(self):
while self.isEmpty:
try : wait() #########
except: pass
self.next = self.next - 1
if not self.next:
self.isEmpty = 1
self.isFull = 0
notify() ########=======> how to do this?
return self.buff[next]
def add(self,c):
while self.isFull:
try: wait() ########===========> this as well
except: pass
self.buff = self.buff[:self.next]+c+self.buff[self.next:]
self.next += 1
if self.next == len(self.buff):
self.isFull= 1
self.isEmpty = 0
notify() #####
class Consumer:
def __init__(self,soup):
self.soup = soup
def run(self):
for i in range(10) :
c = self.soup.eat();
print "Ate a letter "+c
try:
sleep(randint(1,3))
except:
pass
class Producer:
def __init__(self,soup):
self.soup = soup
self.alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def run(self):
for i in range(10):
c = self.alphabet[randint(1,27)]
self.soup.add(c);
print "Added "+c+" to the soup"
try: sleep(randint(1,3))
except: pass
def main():
s = Soup()
p1 = Producer(s)
s1 = Consumer(s)
t1 = threading.Thread(target=p1.run)
t2 = threading.Thread(target=s1.run)
t1.start()
t2.start()
try :
t1.join()
t2.join()
except:
print "The producer or consumer thread's join() was interrupted..."
if __name__ == '__main__':
main()