15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

18 def writer(queue, loops):<br />

19 for i in range(loops):<br />

20 writeQ(queue)<br />

21 sleep(randint(1, 3))<br />

22<br />

23 def reader(queue, loops):<br />

24 for i in range(loops):<br />

25 readQ(queue)<br />

26 sleep(randint(2, 5))<br />

27<br />

28 funcs = [writer, reader]<br />

29 nfuncs = range(len(funcs))<br />

30<br />

31 def main():<br />

32 nloops = randint(2, 5)<br />

33 q = Queue(32)<br />

34<br />

35 threads = []<br />

36 for i in nfuncs:<br />

37 t = MyThread(funcs[i], (q, nloops),<br />

38 funcs[i].__name__)<br />

39 threads.append(t)<br />

40<br />

41 for i in nfuncs:<br />

42 threads[i].start()<br />

43<br />

44 for i in nfuncs:<br />

45 threads[i].join()<br />

46<br />

47 print 'all DONE'<br />

48<br />

49 if __name__ == '__main__':<br />

50 main()<br />

Here is the output from one execution of this script:<br />

$ prodcons.py<br />

starting writer at: Sun Jun 18 20:27:07 2006<br />

producing object for Q... size now 1<br />

starting reader at: Sun Jun 18 20:27:07 2006<br />

consumed object from Q... size now 0<br />

producing object for Q... size now 1<br />

consumed object from Q... size now 0<br />

producing object for Q... size now 1<br />

producing object for Q... size now 2<br />

producing object for Q... size now 3<br />

consumed object from Q... size now 2<br />

consumed object from Q... size now 1<br />

writer finished at: Sun Jun 18 20:27:17 2006<br />

consumed object from Q... size now 0<br />

reader finished at: Sun Jun 18 20:27:25 2006<br />

all DONE<br />

As you can see, the producer and consumer do not necessarily alternate in execution. (Thank goodness

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!