关于下列python多线程代码输出效果的疑问?
本文介绍了关于下列python多线程代码输出效果的疑问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
下面代码是《python核心编程》关于多线程编程一章中的一个例子:
#!/usr/bin/env python
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)
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()
书上显示的输出结果是这样的
我自己打了一遍,输出结果是这样的
可以看到,我的loop0和loop1的显示内容混合到一起了,这样是对的吗?为什么会这样?
解决方案
这里需要加锁,标准输出是共享资源,大家都可以同时向屏幕写东西,所以可能混乱。
这里需要加入互斥锁,告诉别的线程,我现在要写,你们先别写,然后写完了告诉别的线程,我写完了,你们可以申请写了。
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()
这篇关于关于下列python多线程代码输出效果的疑问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文