簡體   English   中英

使用 Python 在多處理中共享變量? (ProcessPoolExecutor())

[英]Variable sharing in Multiprocessing with Python? (ProcessPoolExecutor())

我想在多個進程之間共享一個變量。

我讀了這個: Shared variable in concurrent.futures.ProcessPoolExecutor() python但它並沒有真正幫助我的代碼。 我也不是這方面的專家,幾周后才開始(一年級學生):)

一旦變量x可用,如何在(所有)線程之間共享它? 這是我到目前為止所擁有的:

import concurrent.futures, time

def share():
    time.sleep(1)
    global x
    x = "hello!"

def printshare():
    while True:
        time.sleep(0.5)
        try:
            print(x)
        except Exception as e:
            print(f"printshare {e}")

def main():
    with concurrent.futures.ProcessPoolExecutor() as executor:    
        executor.submit(share)
        executor.submit(printshare)

if __name__ == '__main__':
    main()

它給了我錯誤:

printshare name 'x' is not defined

讓它工作:

def foo(x):
    time.sleep(1)
    x.string = 'hello'


def foo2(x):
    time.sleep(1.5)
    print(x.string)

def main():
    x = Value('i')

    with concurrent.futures.ProcessPoolExecutor() as executor:    
        executor.submit(foo(x))
        executor.submit(foo2(x))

if __name__ == '__main__':
    main()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM