这里需要加锁,标准输出是共享资源,大家都可以同时向屏幕写东西,所以可能混乱。
这里需要加入互斥锁,告诉别的线程,我现在要写,你们先别写,然后写完了告诉别的线程,我写完了,你们可以申请写了。
loop 函数写成:
import threading
#创建锁
mutex = threading.Lock()
def loop(nloop, nsec):
#锁定
mutex.acquire()
print 'start loop', nloop, 'at:', ctime()
sleep(nsec)
print 'loop', nloop, 'done at:', ctime()
#释放
mutex.release()
所有代码为:
#!/usr/bin/env python
# encoding: utf-8
import threading
from time import sleep, ctime
loops = [ 4, 2 ]
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):
apply(self.func, self.args)
# 创建锁
mutex = threading.Lock()
def loop(nloop, nsec):
# 锁定
mutex.acquire()
print 'start loop', nloop, 'at:', ctime()
sleep(nsec)
print 'loop', nloop, 'done at:', ctime()
# 释放
mutex.release()
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()