单线程和多线程执行对比—Python多线程编程
单线程和多线程执行对比
本章使用递归求斐波那契、阶乘与累加函数的执行来对比单线程与多线程;
斐波那契、阶乘与累加(mtfacfib.py):
1 import threading 2 from time import sleep, ctime 3 4 class MyThread(threading.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 %s at:%s' % (self.name, ctime())) 16 self.res = self.func(*self.args) 17 print('%s finished at:%s' % (self.name, ctime())) 18 19 20 def fib(x): 21 sleep(0.005) 22 if x < 2: 23 return 1 24 return (fib(x-2) + fib(x-1)) 25 26 def fac(x): 27 sleep(0.1) 28 if x < 2: 29 return 1 30 return (x * fac(x-1)) 31 32 def sum(x): 33 sleep(0.1) 34 if x < 2: 35 return 1 36 return (x + sum(x-1)) 37 38 funcs = [fib, fac, sum] 39 n = 12 40 41 def main(): 42 nfuncs = range(len(funcs)) 43 44 print('*** SINGLE THREAD') 45 for i in nfuncs: 46 print('starting %s at:%s' % (funcs[i].__name__, ctime())) 47 print(funcs[i](n)) 48 print('%s finished at:%s' % (funcs[i].__name__, ctime())) 49 50 print('\n*** MULTIPLE THREADS') 51 threads = [] 52 for i in nfuncs: 53 t = MyThread(funcs[i], (n,), funcs[i].__name__) 54 threads.append(t) 55 56 for i in nfuncs: 57 threads[i].start() 58 59 for i in nfuncs: 60 threads[i].join() 61 print(threads[i].getResult()) 62 63 print('all Done') 64 65 if __name__ == '__main__': 66 main()
输出结果为:
1 E:\Project\Test_Temporary>python mtfacfib.py 2 *** SINGLE THREAD 3 starting fib at:Fri Jul 27 08:53:18 2018 4 233 5 fib finished at:Fri Jul 27 08:53:20 2018 6 starting fac at:Fri Jul 27 08:53:20 2018 7 479001600 8 fac finished at:Fri Jul 27 08:53:22 2018 9 starting sum at:Fri Jul 27 08:53:22 2018 10 78 11 sum finished at:Fri Jul 27 08:53:23 2018 12 13 *** MULTIPLE THREADS 14 starting fib at:Fri Jul 27 08:53:23 2018 15 starting fac at:Fri Jul 27 08:53:23 2018 16 starting sum at:Fri Jul 27 08:53:23 2018 17 fac finished at:Fri Jul 27 08:53:24 2018 18 sum finished at:Fri Jul 27 08:53:24 2018 19 fib finished at:Fri Jul 27 08:53:25 2018 20 233 21 479001600 22 78 23 all Done
-
以单线程运行时,只是简单的依次调用每个函数,并在函数执行结束后立即显示相应结果;
-
以多线程模式运行时,不会立即显示结果,而是等线程都结束后再调用 getResult() 方法来最终显示每个函数的返回值。
新手写博客,把自己学习过程中的收获和问题在博客上记录。欢迎大家在评论区进行指点,希望能越来越好。