例 18.4
import threading
from time import sleep,ctime
loops = [4,2]
def loop(nloop,nsec):
print ('start loop', nloop, 'at:',ctime())
sleep(nsec)
print ('loop', nloop, 'done at:',ctime())
def main():
print ('starting at:', ctime())
threads = []
nloops = range(len(loops))
for i in nloops:
t = threading.Thread(target=loop, args=(i,loops[i]))
threads.append(t)
for i in nloops: # starting threads
threads[i].start()
for i in nloops: # wait for all
threads[i].join() # threads to finish
print ('all done at:', ctime())
if __name__ == '__main__':
main()
结果:
starting at: Fri Oct 5 17:33:41 2018
start loop 0 at: Fri Oct 5 17:33:41 2018
start loop 1 at: Fri Oct 5 17:33:41 2018
loop 1 done at: Fri Oct 5 17:33:43 2018
loop 0 done at: Fri Oct 5 17:33:45 2018
all done at: Fri Oct 5 17:33:45 2018
例18.5
# 例18.5
import threading
from time import sleep,ctime
class ThreadFunc(object):
def __init__(self,func,args,name=' '):
self.name=name
self.func=func
self.args=args
def __call__(self):
# apply(self.func,self.args) # P2,但是P3不再支持apply函数
self.func(*self.args)
loops = [4,2]
def loop(nloop,nsec):
print ('start loop', nloop, 'at:',ctime())
sleep(nsec)
print ('loop', nloop, 'done at:',ctime())
def main():
print ('starting at:', ctime())
threads = []
nloops = range(len(loops))
# create all threads
for i in nloops:
t = threading.Thread(target=ThreadFunc(loop, (i,loops[i]),loop.__name__)) #
threads.append(t)
for i in nloops: # starting threads
threads[i].start()
for i in nloops: # wait for completion
threads[i].join()
print ('all done at:', ctime())
if __name__ == '__main__':
main()
结果:
starting at: Fri Oct 5 17:48:01 2018
start loop 0 at: Fri Oct 5 17:48:01 2018
start loop 1 at: Fri Oct 5 17:48:01 2018
loop 1 done at: Fri Oct 5 17:48:03 2018
loop 0 done at: Fri Oct 5 17:48:05 2018
all done at: Fri Oct 5 17:48:05 2018
18.5.2 斐波那契、阶乘和累加和
# 例18.6
import threading
from time import sleep, ctime
loops = (4,2)
# 子类化Thread类,而不是创建它的实例,好处:更灵活地定制我们的线程对象
class MyThread(threading.Thread):
def __init__(self,func,args,name=' '):
threading.Thread.__init__(self)
self.name=name
self.func=func
self.args=args
def run(self):
self.func(*self.args)
def loop(nloop,nsec):
print ('start loop', nloop, 'at:', ctime)
sleep(nsec)
print ('loop', nloop, 'done at:', ctime)
def main():
print ('starting at:',ctime())
threads=[]
nloops=range(len(loops))
for i in nloops:
t = MyThread(loop, (i,loops[i]), loop.__name__)
threads.append(t)
for i in nloops:
threads[i].start()
for i in nloops:
threads[i].join()
print ('all done at:',ctime())
if __name__ == '__main__':
main()
结果:
starting at: Fri Oct 5 18:01:14 2018
start loop 0 at: <built-in function ctime>
start loop 1 at: <built-in function ctime>
loop 1 done at: <built-in function ctime>
loop 0 done at: <built-in function ctime>
all done at: Fri Oct 5 18:01:18 2018
# 例18.7 MyThread子类化Thread (myThread.py)
# 把子类单独放在一个模块中,并加上一个getResult()函数用以返回函数的运行结果
# 让MyThread类尽可能地通用(同时适应有输出和没输出的函数),等到要结束时才会调用getResult()函数,并在最后显示每个函数的结果
import threading
from time import ctime,sleep
class MyThread(threading.Thread):
def __init__(self,func,args,name=' '):
threading.Thread.__init__(self)
self.name=name
self.func=func
self.args=args
def getResult(self):
return self.res
def run(self):
print ('starting', self.name, 'at:', ctime())
self.res = self.func(*self.args)
print (self.name, 'finished at:', ctime())
# 18.8
from myThread import MyThread
from time import ctime,sleep
def fib(x):
sleep(0.005)
if x < 2: return 1
return (fib(x-2)+fib(x-1))
def fac(x):
sleep(0.1)
if x < 2: return 1
return (x * fac(x-1))
def sum(x):
sleep(0.1)
if x < 2: return 1
return (x + sum(x-1))
funcs = (fib,fac,sum)
n = 12
def main():
nfuncs = range(len(funcs))
print ('*** SINGLE THREAD')
for i in nfuncs:
print ('starting', funcs[i].__name__, 'at:', ctime())
print (funcs[i](n))
print (funcs[i].__name__, 'finished at:', ctime())
print ('\n*** MULTIPLE THREADS')
threads = []
for i in nfuncs:
t = MyThread(funcs[i], (n,), funcs[i].__name__)
threads.append(t)
for i in nfuncs:
threads[i].start()
for i in nfuncs:
threads[i].join()
print (threads[i].getResult())
print ('all DONE')
if __name__ == '__main__':
main()
结果:
*** SINGLE THREAD
starting fib at: Fri Oct 5 21:15:29 2018
233
fib finished at: Fri Oct 5 21:15:32 2018
starting fac at: Fri Oct 5 21:15:32 2018
479001600
fac finished at: Fri Oct 5 21:15:33 2018
starting sum at: Fri Oct 5 21:15:33 2018
78
sum finished at: Fri Oct 5 21:15:34 2018
*** MULTIPLE THREADS
starting fib at: Fri Oct 5 21:15:34 2018
starting fac at: Fri Oct 5 21:15:34 2018
starting sum at: Fri Oct 5 21:15:34 2018
fac finished at: Fri Oct 5 21:15:35 2018
sum finished at: Fri Oct 5 21:15:35 2018
fib finished at: Fri Oct 5 21:15:37 2018
233
479001600
78
all DONE
18.5.4 生产者-消费者问题和Queue模块
# python3是queue,Python2是Queue
from random import randint
from time import ctime,sleep
from queue import Queue # python3是queue,Python2是Queue
from myThread import MyThread # 18.7
from time import ctime,sleep
def writeQ(queue):
print ('producing object for Q...', queue.put('xxx',1))
print ('size now', queue.qsize())
def readQ(queue):
val = queue.get(1)
print ('consumed object from Q... size now', queue.qsize())
def writer(queue, loops):
for i in range(loops):
writeQ(queue)
sleep(randint(1,3))
def reader(queue, loops):
for i in range(loops):
readQ(queue)
sleep(randint(2,5))
funcs = [writer, reader]
nfuncs = range(len(funcs))
def main():
nloops = randint(2,5)
q = Queue(32)
threads=[]
for i in nfuncs:
t = MyThread(funcs[i], (q,nloops), funcs[i].__name__)
threads.append(t)
for i in nfuncs:
threads[i].start()
for i in nfuncs:
threads[i].join()
print ('all DONE')
if __name__=='__main__':
main()
结果:
starting writer at: Fri Oct 5 21:32:53 2018
producing object for Q... None
size now 1
starting reader at: Fri Oct 5 21:32:53 2018
consumed object from Q... size now 0
producing object for Q... None
size now 1
consumed object from Q... size now 0
producing object for Q... None
size now 1
producing object for Q... None
consumed object from Q... size now 1
size now 1
consumed object from Q... size now 0
writer finished at: Fri Oct 5 21:33:04 2018
reader finished at: Fri Oct 5 21:33:08 2018
all DONE
starting writer at: Fri Oct 5 22:33:21 2018
producing object for Q... None
size now 1
starting reader at: Fri Oct 5 22:33:21 2018
consumed object from Q... size now 0
producing object for Q... None
size now 1
producing object for Q... None
size now 2
consumed object from Q... size now 1
writer finished at: Fri Oct 5 22:33:27 2018
consumed object from Q... size now 0
reader finished at: Fri Oct 5 22:33:33 2018
all DONE