【发布时间】:2015-06-11 06:08:33
【问题描述】:
据我了解,当您在 Python 中实现全局锁时,这应该为激活锁的线程保留标准输出,从而防止其他线程在线程释放锁之前使用标准输出。
这是否意味着在下面的代码中,线程“a”中的循环应该在线程“b”中的函数输出任何内容之前完成?当我运行它时,线程“c”打印的“7”有时会在“a”的输出中交错。
我希望输出始终如下:
5
5
5
5
5
6
7
但我得到了:
5
7
5
5
5
6
代码:
import threading, time
thelock = threading.Lock()
def afunc(var):
with thelock:
for i in range(5):
time.sleep(.0002)
print(var)
def bfunc(var):
print(var)
a=threading.Thread(target=afunc, args=(5,))
b=threading.Thread(target=bfunc, args=(6,))
c=threading.Thread(target=bfunc, args=(7,))
a.start()
b.start()
c.start()
这适用于 OS X 10.10.3 中的 Python 3.4.3。直接在 OS X 终端或 PyCharm 4.5.1 中运行文件时会发生相同的行为。
【问题讨论】:
标签: python multithreading thread-safety