Python Windows中_线程模块的奇怪输出
在学习线程时,我尝试了以下示例代码:Python Windows中_线程模块的奇怪输出,python,multithreading,Python,Multithreading,在学习线程时,我尝试了以下示例代码: 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
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上的代码似乎是错误的)?一个进程中只有一个标准输出缓冲区,并且
print
不是线程安全的。在任何操作系统上都可以得到这样的乱码输出。它是定时和缓冲的组合,CentOS和Windows上的控制台输出是不同的。您需要同步缓冲输出,例如使用打印
周围的锁
线程的一个特点是,除非以某种方式进行同步,否则您不知道线程的执行顺序。尽管看起来CentOS是“对的”,Windows是“错的”,但您很幸运在CentOS上获得了该序列(或不幸运,取决于您的if观点)我知道多个线程同时工作可能会导致问题。但是这段代码一个接一个地运行它们,并且几乎在瞬间退出。为什么它不起作用?为什么你说t执行“一个接一个”?在开始下一个循环之前,您不会等待每个循环完成。因为我在每个While循环中只启动一个线程,并且只有当脚本接收到除“q”之外的任何输入时,我才能继续执行下一个循环。那么,您是否等待每个循环完成后再单击?请记住,
input()
也使用与工作线程相同的IO系统。