gpt4 book ai didi

python - 在Python中使用start_new_thread控制多个线程流

转载 作者:太空宇宙 更新时间:2023-11-03 18:31:10 25 4
gpt4 key购买 nike

我在开发一个工作流程时得到了令人困惑的结果,该工作流程重复一个需要按准确时间表运行的快速流程,每个实例都由一个可以在自己的时间运行的较慢的函数成功。代码是:

from thread import start_new_thread
import datetime
import time

# log text with current timestamp
def log_event(msg=''):
with open('log.txt', "a") as myfile:
timestring = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
myfile.write(timestring + ' - ' + msg + '\n')

def new_thread(asynchronous, stage):
stage -= 1
if stage < 0:
return

if asynchronous:
log_event( 'new process, stage ' + str(stage) )
start_new_thread(new_thread, (False, stage))
log_event( 'start slow process, stage ' + str(stage) )
time.sleep(5) # simulate slow process to run asynchronously
log_event( 'end slow process, stage ' + str(stage) )

else:
log_event( 'continuing process, stage ' + str(stage) )
time.sleep(2)
start_new_thread(new_thread, (True, stage))

new_thread(True, 3)
log_event('end')

.. 记录以下内容:

2014-03-12 21:11:18 - new process, stage 2
2014-03-12 21:11:18 - continuing process, stage 1
2014-03-12 21:11:18 - start slow process, stage 2
2014-03-12 21:11:20 - new process, stage 0
2014-03-12 21:11:20 - start slow process, stage 0
2014-03-12 21:11:23 - end slow process, stage 2
2014-03-12 21:11:23 - end
2014-03-12 21:11:25 - end slow process, stage 0

我很困惑为什么缺少一些报告 - 例如新流程,阶段 1,阶段 0 和 2 的继续流程等。我也对奇怪的顺序感到困惑:例如我希望缓慢的过程能够按顺序开始和结束。我可能错过了一些关于它是如何工作的。

非常感谢您知道我哪里出错了。

最佳答案

这种代码会让人们根本不推荐线程 - 您可能会在打开日志文件时遇到竞争条件,因为您在以下位置重新打开它每个线程。即使您“ sleep ”的时间间隔很长,您也会启动一些线程,在它们的启动之间没有间隔 - (每对“异步”和“同步”新线程没有人工等待(调用 sleep),只有几行代码将它们分开)。因此,可能发生的情况是,同时使用不同的文件描述符写入日志文件,并且这些写入之一只是被丢弃。

为此,您可以为程序全局打开日志文件,并在所有线程中重新使用打开文件对象 - 这样,操作系统就可以在全局范围内打开该程序的日志文件。可能会处理多个写入文件的调用。但是,另一方面,正如您所看到的,此类问题只会随着系统的增长而扩大:这就是为什么新 Python 版本中的“大新闻”是名为 asyncio 的异步框架。 (A.K.A. Tulip) - 已向后移植到较旧的 Pythona,包括 Python 2.7 作为 Trollius - 它们提供了与线程不同的并发编程范例,如果您正在处理的项目很重要,那么值得关注。

关于python - 在Python中使用start_new_thread控制多个线程流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22364139/

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