这里选自python核心编程第二版的例子
threading模块的多线程实现
两种方式.
第一种提供参数用threading.Thread去构造
import threading
from time import sleep, ctime
loops = [4, 2]
def loop(nloop, nsec):
print 'start loop', nllp, 'at:', ctime()
sleep(nsec)
print 'loop', nloop, 'done at:', ctime()
def main():
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: # start threads
threads[i].start()
for i in nloops: # wait for all
threads[i].join() # threads to finish
if __name__ == '__main__':
main()
该方法再去在Thread对象构造时, 需要传入工作的函数, 以及工作函数的参数.
但是这里可以将传入的target变为一个callable 对象, 直接在构造Thread的时候
构造一个callable对象丢进去. 这样就不用传入 args参数啦.
可是这样仍然不够直观.
所以我们可以通过使用继承threading.Thread的方法来实现
这是第二种方法哟:
import threading
from time import sleep, ctime
loops = (4, 2)
class MyThread(threading.Thread):
def __init__(self, func, args, name=""):
super(MyThread, self).__init__(self)
self.name = name
self.func = func
self.args = args
def run(self):
apply(self.func, self.args) #apply 间接的调用函数
def loop(nloop, nsec):
print 'start loop', nllp, 'at:', ctime()
sleep(nsec)
print 'loop', nloop, 'done at:', ctime()
def main():
threads = []
nloops = range(len(loops))
for i in nloops:
t = MyThread(loop, (i, loops[i]),
loop.__name__)
threads.append(t)
for i in nloops: # start threads
threads[i].start()
for i in nloops: # wait for all
threads[i].join() # threads to finish
if __name__ == '__main__':
main()
而且threading模块中一个神奇的类
Event
说明是:
A factory function that returns a new event object. An event manages a flag that can be set to true with the set() method and reset to false with the clear() method. The wait() method blocks until the flag is true.
默认flag是 False
如果要设置为True 就调用set方法,
如果要重置设置为False就地爱用clear方法.
调用wait()方法会阻塞, 直到flag是True.
一个很简单的方法同步线程.