2017-05-06 96 views
1

我有一個程序執行一些長時間運行的同步任務,即使其中一些任務尚未完成,也可能需要退出程序。以下是一個簡單的程序,在main()開始這樣的任務。之後立即返回main(),因此程序應該退出。在默認執行程序中的任務仍在運行時退出程序

import asyncio, time 

def synchronous_task(): 
    for i in range(5): 
     print(i) 
     time.sleep(1) 

async def main(): 
    loop.run_in_executor(None, synchronous_task) 

loop = asyncio.get_event_loop() 
loop.run_until_complete(main()) 

print('Main thread exiting.') 

但不是運行該腳本時,我得到這樣的:

$ python3.5 test3.py 
0 
Main thread exiting. 
1 
2 
3 
4 

什麼是處理這種情況的預期呢?事件循環的默認執行程序已經使用守護程序線程並終止程序,而不清理在我的情況下可以,但我不想使用os._exit()

+0

你得到**主線程退出**,是不是你想要的? – stovfl

+0

@stovfl不,我想處理終止。但正如你所看到的,它在主線程退出後繼續打印到控制檯。 – Feuermurmel

+0

你想'終止/殺死''synchronous_task'。你嘗試過'loop.close()'嗎? – stovfl

回答

0

你的問題更多關於如何殺死一個線程。詳細信息請查看this

解決方案與活動將是:

import asyncio, time 
from functools import partial 
import threading 
import concurrent 


def synchronous_task(ev): 
    for i in range(5): 
     if ev.isSet(): 
      print('terminating thread') 
      return 
     print(i) 
     time.sleep(1) 

async def main(): 
    ev = threading.Event() # see: https://stackoverflow.com/a/325528/1113207 

    loop.run_in_executor(None, partial(synchronous_task, ev)) 
    await asyncio.sleep(2) # give thread some time to execute, to see results 

    ev.set() 


loop = asyncio.get_event_loop() 
executor = concurrent.futures.ThreadPoolExecutor(5) 
loop.set_default_executor(executor) 
try: 
    loop.run_until_complete(main()) 
finally: 
    loop.run_until_complete(loop.shutdown_asyncgens()) 
    executor.shutdown(wait=True) # see: https://stackoverflow.com/a/32615276/1113207 
    loop.close() 

print('Main thread exiting.') 

結果:

0 
1 
terminating thread 
Main thread exiting. 
[Finished in 2.2s] 
+0

謝謝你的回答。我原來的問題不是關於如何突然終止一個線程,然後我會使用子進程。這是關於如何終止整個過程_線程仍然running_。也許我的問題寫得不夠清楚。在此期間,我實際上實施了類似於您的建議的內容。而不是'ev.isSet()'我會寫'ev.wait(1)'並且移除對'time.sleep()'的調用。 – Feuermurmel

相關問題