15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

16 def sum(x):<br />

17 sleep(0.1)<br />

18 if x < 2: return 1<br />

19 return (x + sum(x-1))<br />

20<br />

21 funcs = [fib, fac, sum]<br />

22 n = 12<br />

23<br />

24 def main():<br />

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

26<br />

27 print '*** SINGLE THREAD'<br />

28 for i in nfuncs:<br />

29 print 'starting', funcs[i].__name__, 'at:', \<br />

30 ctime()<br />

31 print funcs[i](n)<br />

32 print funcs[i].__name__, 'finished at:', \<br />

33 ctime()<br />

34<br />

35 print '\n*** MULTIPLE THREADS'<br />

36 threads = []<br />

37 for i in nfuncs:<br />

38 t = MyThread(funcs[i], (n,),<br />

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

40 threads.append(t)<br />

41<br />

42 for i in nfuncs:<br />

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

44<br />

45 for i in nfuncs:<br />

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

47 print threads[i].getResult()<br />

48<br />

49 print 'all DONE'<br />

50<br />

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

52 main()<br />

Running in single-threaded mode simply involves calling the functions one at a time and displaying the<br />

corresponding results right after the function call.<br />

When running in multithreaded mode, we do not display the result right away. Because we want to keep<br />

our MyThread class as general as possible (being able to execute callables that do and do not produce<br />

output), we wait until the end to call the geTResult() method to finally show you the return values of<br />

each function call.<br />

Because these functions execute so quickly (well, maybe except for the Fibonacci function), you will<br />

notice that we had to add calls to sleep() to each function to slow things down so that we can see how<br />

threading may improve performance, if indeed the actual work had varying execution times you<br />

certainly wouldn't pad your work with calls to sleep(). Anyway, here is the output:<br />

$ mtfacfib.py<br />

*** SINGLE THREAD<br />

starting fib at: Sun Jun 18 19:52:20 2006

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

Saved successfully!

Ooh no, something went wrong!