Python ThreadPoolExecutor 中的同步

问题描述 投票:0回答:0

我有以下代码:

from concurrent.futures import ThreadPoolExecutor
li=[]
def func1(arg1):
    some code...
    li.append(content)

executor = ThreadPoolExecutor(max_workers=20)

for i in range(n):
    executor.submit(func1,arg1)

executor.shutdown(wait=True)

不同步,有时耗时太长,数据丢失。

我尝试在函数定义中像这样附加到列表之前使用线程锁定和释放

import threading
from concurrent.futures import ThreadPoolExecutor
lock=threading.Lock()
li=[]
def func1(arg1):
    some code...
    lock.acquire()
    li.append(content)
    lock.realease()

executor = ThreadPoolExecutor(max_workers=20)

for i in range(n):
    executor.submit(func1,arg1)

executor.shutdown(wait=True)

这导致列表最后为空。

python multithreading synchronization threadpool race-condition
© www.soinside.com 2019 - 2024. All rights reserved.