[英]How can I multi-thread or multi-process a large itertools.combinations in python efficiently?
[英]How can I multi-thread 3 different functions that return the same value and pick the fastest
我正在使用線程模塊,並具有3個不同的函數,它們返回相同的值,但使用不同的方法返回該值。
我想要ID,並將其命名為my_id
例如:
功能1:使用移動端點抓取網站並為my_id解析json
功能2:使用桌面終結點抓取網站並為my_id解析json
功能3:抓取桌面網站HTML並找到my_id
我想做的是同時運行每個函數,無論哪個函數返回my_id最快,我都會接受它並繼續執行我的代碼。
最好的方法是什么?
您可以使用concurrent.futures.
創建三個線程,並使用concurrent.futures.Executor.submit()
啟動它們。這將為您返回每個線程的將來對象。
那么你也能
concurrent.futures.wait(fs, timeout=None, return_when=FIRST_COMPLETED)
它將阻塞主線程,直到3個子線程之一完成。
然后,您可以繼續使用您的結果。
concurrent.futures.wait Returns a named 2-tuple of sets. The first set, named done and not_done
您可以使用result()方法從完成的期貨對象中獲取結果,並可以使用Executor.shutdown()安全地關閉執行程序。
您可以將對象添加到列表中,然后像futures = [] for task in task_list: futures.append(executor.submit(task.run)) concurrent.futures.wait(futures,timeout=None,return_when=FIRST_COMPLETED)
那樣啟動它們: futures = [] for task in task_list: futures.append(executor.submit(task.run)) concurrent.futures.wait(futures,timeout=None,return_when=FIRST_COMPLETED)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.