[英]While loop won't break in python multiprocessing
由於我沒有收到任何反饋,對於這個問題,我在這里重新概念化(並簡化)了這個問題。 在這種簡化的情況下,我想知道如何重新啟動不會中斷多處理隊列的 while 循環。
我想使用multiprocessing
庫在多個內核上運行一個函數。
p = multiprocessing.Pool(5) # Start a pool with 5 cores
analysis = p.map(function_to_call,'abcdefghij') # Call function_to_call on every core
# each time with a different letter from
# string 'abcdefghij' and collect results
print(analysis)
def function_to_call(arg):
result = []
time = timeit.default_timer() # timeit library needed
time_even = int(str(time)[-1]) # get last number of time
########## below can't be changed ###########
while True:
if (time_even % 2) == 0: # if last number is even, do stuff
result.append('problem')
else: # else append arg to result
result.append(str(arg))
break
########## above can't be changed ###########
print(result)
return(result) # and return result
編譯腳本的時間總是不同的。 就我而言,終端中的輸出是:
['b']
['c']
['g']
['h']
['i']
['e'] # <--- note that the process run in parallel and not serial
結論是,當使用參數'a'
、 'd'
、 'f'
和'j'
調用函數調用時,它會卡在 while 循環中(因為在這些情況下,時間戳的最后一個數字顯然是偶數) . 但是,如果我在 while 循環中的 if 語句中添加and False
以使其始終中斷,則會將以下內容打印到終端,表明一切正常(打印(結果)已編譯):
['a']
['b']
['d']
['c']
['g']
['h']
['f']
['j']
['i']
['e']
[['a'], ['b'], ['c'], ['d'], ['e'], ['f'], ['g'], ['h'], ['i'], ['j']]
在我正在處理的腳本中,可能會發生 function_to_call 在某些情況下不返回輸出的情況。 但是,多次重新運行該函數最終會輸出結果(我想用時間戳來模仿)。 因此,我想調整我的腳本,以便在不返回輸出時使用相同的參數調用 function_to_call。
不幸的是,我要調用的函數需要幾個小時才能結束。 所以我不想強迫它在某個預設時間值后中斷。 我會感謝每一個評論和所有建議!
以指數增加的超時時間重新運行它:
from stopit import ThreadingTimeout
timeout = 3600 # should probably be set slightly above the expected runtime
while True:
with ThreadingTimeout(timeout) as timeout_ctx:
result = function_to_call()
if timeout_ctx.state != timeout_ctx.TIMED_OUT:
return result
timeout *= 2
這樣你就可以確定你平均不會做超過兩倍的工作。
注意:我在我的示例中使用了 stopit 庫https://github.com/glenfant/stopit
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.