分别用单线程和多线程运行斐波那契、阶乘和累加和

threading 的Thread类是用来创建线程的对象,其中,有三种方法可创建线程对象

1.创建一个Thread的实例,传给它一个函数。

2.创建一个Thread的实例,传给它一个可调用的类对象。

3.从Thread派生出一个子类,创建一个这个子类的实例。

 

下面将通过第三种方式派生类来创建线程对象:

自定义继承于threading.Thread的通用MyThread类

 1 import threading
 2 from time import ctime
 3 
 4 class MyThread(threading.Thread):   #创建通用类MyThread子类化Thread
 5     def __init__(self,func,args,name=''):
 6         threading.Thread.__init__(self)
 7         self.name=name
 8         self.func=func
 9         self.args=args
10 
11     def getResult(self):    #用于返回调用线程的函数的结果
12         return self.res
13 
14     def run(self):
15         print('starting',self.name,'at:',ctime())
16         self.res=self.func(*self.args)
17         print(self.name,'finished at:',ctime())

 

分别用单线程和多线程实现斐波那契、阶乘、和累加和

 1 from myThread import MyThread
 2 from time import ctime,sleep
 3 
 4 def fib(x): #斐波那契函数
 5     sleep(0.005)
 6     if x<2:
 7         return 1
 8     else:
 9         return (fib(x-2)+fib(x-1))
10 
11 def fac(x): #求阶乘
12     sleep(0.1)
13     if x<2:
14         return 1
15     else:
16         return(x*fac(x-1))
17 
18 def sum(x): #求1到x的和
19     sleep(0.1)
20     if x<2:
21         return 1
22     else:
23         return(x+sum(x-1))
24 
25 
26 funcs=[fib,fac,sum]
27 n=12
28 
29 def main():
30     nfuncs=range(len(funcs))    #3
31 
32     print('*********SINGLE THREAD') #单线程
33     for i in nfuncs:
34         print('starting',funcs[i].__name__,'at:',ctime())
35         print(funcs[i](n))  #分别调用三个函数,并将12作为参数传入
36         print(funcs[i].__name__,'finished at:',ctime())
37 
38     print('\n******MULTIPLE THREADS')   #多线程
39     threads=[]      #线程池
40     for i in nfuncs:
41         t=MyThread(funcs[i],(n,),funcs[i].__name__) #传入函数对象,参数,函数名实例化线程
42         threads.append(t)                           #将实例化后的线程加入线程池
43 
44     for i in nfuncs:                               #开启所有线程
45         threads[i].start()
46 
47     for i in nfuncs:
48         threads[i].join()                       #挂起程序直到线程结束
49         print('********show the result')
50         print(threads[i].getResult())
51 
52     print('all DONE')
53 
54 if __name__=='__main__':
55     main()

 

结果如下

 1 *********SINGLE THREAD
 2 starting fib at: Sun Apr  1 15:57:06 2018
 3 233
 4 fib finished at: Sun Apr  1 15:57:09 2018
 5 starting fac at: Sun Apr  1 15:57:09 2018
 6 479001600
 7 fac finished at: Sun Apr  1 15:57:10 2018
 8 starting sum at: Sun Apr  1 15:57:10 2018
 9 78
10 sum finished at: Sun Apr  1 15:57:11 2018
11 
12 ******MULTIPLE THREADS
13 starting fib at: Sun Apr  1 15:57:11 2018
14 starting fac at: Sun Apr  1 15:57:11 2018
15 starting sum at: Sun Apr  1 15:57:11 2018
16 fac finished at: Sun Apr  1 15:57:12 2018
17 sum finished at: Sun Apr  1 15:57:12 2018
18 fib finished at: Sun Apr  1 15:57:13 2018
19 ********show the result
20 233
21 ********show the result
22 479001600
23 ********show the result
24 78
25 all DONE

 

posted @ 2018-04-01 16:09  xajh00789  阅读(797)  评论(0编辑  收藏  举报