例子:
import multiprocessing as mp
counter = mp.Value('i', 0)
def test_fun(i):
global counter
with counter.get_lock():
counter.value = 1
def main():
global counter
with mp.Pool(4) as p:
result = p.map(test_fun, range(4))
print(counter.value)
if __name__ == "__main__":
main()
預期輸出為 4,因為該值是共享的,但在 Mac 上輸出 0。
它在使用 linux 或使用fork時作業,但我希望它與 Spawn 一起作業。
uj5u.com熱心網友回復:
只需將計數器宣告移動到您的主函式,然后將其設定為子初始化程式中的全域變數,就像在 Windows 上完成的那樣。
import multiprocessing as mp
def setup_fn(value):
global counter
counter = value
def test_fun(i):
global counter
with counter.get_lock():
counter.value = 1
def main():
counter = mp.Value('i', 0)
with mp.Pool(4, initializer=setup_fn, initargs=(counter,)) as p:
result = p.map(test_fun, range(4))
print(counter.value)
if __name__ == "__main__":
main()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/517047.html
上一篇:如何在單獨的(Ruby)執行緒中保持Tempfile內容不為空?
下一篇:c中的執行緒安全拆分ip:埠
