gpt4 book ai didi

python - 我如何在 python 中进行线程化?

转载 作者:行者123 更新时间:2023-11-28 19:41:07 25 4
gpt4 key购买 nike

使用本网站的代码:http://www.saltycrane.com/blog/2008/09/simplistic-python-thread-example/

代码是

import time
from threading import Thread

def myfunc(i):
print "sleeping 5 sec from thread %d" % i
time.sleep(5)
print "finished sleeping from thread %d" % i

for i in range(10):
t = Thread(target=myfunc, args=(i,))
t.start()

我得到了这个输出:

sleeping 5 sec from thread 0
sleeping 5 sec from thread 1
sleeping 5 sec from thread 2
sleeping 5 sec from thread 3
sleeping 5 sec from thread 4
sleeping 5 sec from thread 5
sleeping 5 sec from thread 6
sleeping 5 sec from thread 7
sleeping 5 sec from thread 8
sleeping 5 sec from thread 9
finished sleeping from thread 0
finished sleeping from thread 2
finished sleeping from thread 4
finished sleeping from thread 1finished sleeping from thread 6finished sleeping from thread 8
finished sleeping from thread 5finished sleeping from thread 7finished sleeping from thread 9

finished sleeping from thread 3

这是怎么回事?我可以接受线程未按顺序打印,因为这是可能的,但为什么它们最后不在换行符上打印?我在 windows xp 下使用 python 2.6

最佳答案

您刚刚发现了为什么使用线程编程很困难 :)

发生的情况是您的所有线程几乎同时被唤醒。一个线程开始打印“finished sleep from thread 1”,在它有机会打印最后一个“\n”之前,另一个线程开始打印“finished sleep from thread 6”,等等。那些换行符并没有被跳过,它们只是四处移动并聚集在其他地方。这可能就是为什么在“finished...3”之前跳过了一行。我的猜测是有许多尾随空白行由于格式化而被删除。

使用threading.Lock围绕您的 print 语句进行同步,以便多个 print 不会同时发生。

关于python - 我如何在 python 中进行线程化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3258603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com