当我学习Threads时,我尝试了以下示例代码:
import _thread
def child(tid):
print('Hello from thread',tid)
def parent():
i=0
while True:
i+=1
_thread.start_new_thread(child,(i,))
if input()=='q':break
parent()
我预期的结果就像
Hello from thread 1
Hello from thread 2
Hello from thread 3
q
我在CentOS 7上使用类似的代码获得了上述结果。但是在Win8上,结果非常奇怪:
Hello from thread
Hello from thread
Hello from thread 1
Hello from thread 2
q
Hello from thread 3
4
5
任何人都可以向我解释为什么相同的代码会产生不同的结果(win8上的那个似乎是错误的)?
答案 0 :(得分:0)
进程中只有一个stdout缓冲区,print
不是线程安全的。你可以在任何操作系统上得到这样的乱码输出。它是时间和缓冲的组合,CentOS和Windows上的控制台输出是不同的。您需要同步缓冲输出,例如使用print
附近的锁定。
除非您以某种方式进行同步,否则您不知道线程将执行的顺序是线程的一项功能。虽然看起来CentOS是“正确的”而Windows是“错误的”,但你很幸运能在CentOS上获得这个序列(或者不幸的是,视你的观点而定)