我是 Python 多处理的新手。我刚遇到一个问题,我希望有一个进程不断检查文件传输是否完成。如果一分钟过去但传输未完成,我想继续使用代码。 我发现实现定时器的一种方法是使用多处理。我将尝试解释我的代码:
import multiprocessing
import time
def isFileTransferDone():
while(transferOngoing()):
#File transfer ongoing.
#Will return false once transfer is finishedand then I expect process p1 to end
print("completed")
def timeout():
for i in range(1000):
time.sleep(1)
if __name__ == "__main__":
p1 = multiprocessing.Process(target=isFileTransferDone)
p2 = multiprocessing.Process(target=timeout)
p1.start()
p2.start()
#I am exepcting the program to wait on the below line untill either p1 is finished or until 60 seconds has passed
if(p1.join() or p2.join(60)):
if p1.is_alive():
p1.terminate()
p2.terminate()
#I would like my program to continue here
我尝试阅读有关 process.join() 的内容。我不确定我是否理解它。我希望它在代码中等待,直到该特定过程完成。也许是 isFileTransferDone() 中的某些东西是错误的。当 while-loop 不再满足时,我希望该过程结束?
我将非常感谢关于我应该如何在这里进行的一些指导:)
首先,
join
返回None
,即False
,所以你的测试...
if(p1.join() or p2.join(60)):
... 总是先等待
p1
完成,然后最多等待 60 秒让 p2
完成。因此,如果 p1
完成的时间超过 60 秒,您仍将等待该完成。如果只需要 1 秒即可完成,那么您将需要额外等待 59 秒才能完成p2
!
解决方法就简单多了:
import multiprocessing
def isFileTransferDone():
"""
while(transferOngoing()):
#File transfer ongoing.
#Will return false once transfer is finishedand then I expect process p1 to end
...
"""
# For demo purposes:
import time
time.sleep(2)
print("completed")
if __name__ == "__main__":
p = multiprocessing.Process(target=isFileTransferDone)
p.start()
p.join(60) # Wait for up to 60 seconds for task to complete
if p.is_alive():
# The process is still running, so kill it:
p.terminate()
timeout = True
else:
# Process completed normally:
timeout = False
# Program continues here after process completes normally or
# 60 seconds have elapsed and we terminated it.
# You can test timeout variable
# to see if timeout occured or not:
print(timeout)