我在开发一个工作流时得到了令人困惑的结果,这个工作流重复一个快速的过程,需要按照准确的时间表运行,每个实例后面都有一个可以在自己的时间内运行的较慢的函数。代码是:
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
我不明白为什么有几个报告丢失了,例如new process, stage 1
,continuing process
阶段0和2,等等。我还对奇怪的顺序感到困惑:例如,我希望缓慢的进程按顺序开始和结束。我可能错过了一些关于这个工作原理的东西。你知道吗
非常感谢你告诉我我错在哪里。你知道吗
这种代码使人们根本不推荐线程,因为在每个线程中重新打开日志文件,所以在打开日志文件时可能会遇到竞争条件。 即使您正在“休眠”大量的时间间隔,您也在启动一些线程,它们之间没有时间间隔(每对“异步”和“同步”新线程都没有人工等待(调用
sleep
),只是将它们分隔开的几行代码)。因此,可能发生的情况是,日志文件被写入,同时使用不同的文件描述符,其中一个写入操作被丢弃。你知道吗为此,您可以全局地打开程序的日志文件,并在所有线程中重新使用open file对象—这样,O.S.可能会处理多个对文件进行写入的调用。但是,另一方面,如您所见,这类问题只会随着系统的增长而扩大:这就是为什么新Python版本中的“大新闻”是称为asyncio(A.K.A.Tulip)的异步框架,它已经为旧的Pythona进行了后端口,包括作为Trollius的Python2.7,它们为并发编程提供了不同的范例如果你正在做的项目很重要的话,这是值得注意的。你知道吗
相关问题 更多 >
编程相关推荐