如何使用并行线程运行无限while循环



我正试图在主线程中与另一个在每次迭代中启动和停止/删除的并行线程一起运行中篇while循环,而不影响while循环。挑战在于,主线程不能等待并行线程,也就是说,无论该迭代中的并行线程是否已经完成,它都应该开始下一次迭代。

我的主要是这样的:

while true
# start iteration and do something
# start parallel thread
parallel_thread = threading.Thread(target=parallel_thread_class.thread_do_something(), daemon = True)
parallel_thread.start()
# end iteration and start new one

此时,主线程(while循环(等待,直到方法parallel_thread_class.thread_do_something()完成,然后才完成当前迭代。

parallel_thread_class.thread_do_something()中的括号调用主线程中的函数,删除括号使构造的线程调用函数,如下

parallel_thread = threading.Thread(target=parallel_thread_class.thread_do_something, daemon = True)

我建议使用asyncio。您可以实现如下:

import asyncio
async def mainTask():
i=0 #iteration counter
while True:
print('Iteration.... ',i) #prints the current iteration number
task2 = asyncio.create_task(secondTask()) #init the other task
await asyncio.sleep(2) #waits 2 secs in the main thread (you can delte this line if your iteration delays making computation)
i+=1 #incremets teh counter of iterations
task2.cancel() #Cancel the task no matter if not copleted
#Your second task prints from 1 to 20 each 0.3 secs
async def secondTask():
for i in range(20):
print('Second Task: {}/20'.format(i+1))
await asyncio.sleep(0.3)

asyncio.run(mainTask())

输出:

Iteration....  0
Second Task: 1/20
Second Task: 2/20
Second Task: 3/20
Second Task: 4/20
Second Task: 5/20
Second Task: 6/20
Second Task: 7/20
Iteration....  1
Second Task: 1/20
Second Task: 2/20
Second Task: 3/20
Second Task: 4/20
Second Task: 5/20
Second Task: 6/20
Second Task: 7/20
Iteration....  2
Second Task: 1/20
Second Task: 2/20
Second Task: 3/20
Second Task: 4/20
Second Task: 5/20
Second Task: 6/20
Second Task: 7/20

正如你所看到的,第二个任务永远不会完成,每次迭代都会重新开始

根据python的文档,

启动((

启动线程的活动。每个线程对象最多只能调用一次。它安排在单独的控制线程中调用对象的run((方法。如果在同一线程对象上多次调用此方法,则会引发RuntimeError。

加入(超时=无(

等待线程终止。这会阻塞调用线程,直到调用其join((方法的线程终止(正常终止或通过未处理的异常终止(,或者直到出现可选超时。

最新更新