Python:如何将相同的锁传递给映射到 ThreadPoolExecutor 的多个线程?

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

假设我不想全局指定锁。如何将相同的锁传递给

ThreadPoolExecutor
中的每个线程?这是不起作用的:

import threading
from concurrent.futures import ThreadPoolExecutor

def main():
    lock = threading.Lock()
    
    with ThreadPoolExecutor(max_workers=10) as executor:
        executor.map(thread_function, range(10), lock)

def thread_function(number: int, lock: threading.Lock):
    with lock:
        print("Hello from the thread with argument: ", number)


if __name__ == '__main__':
    main()

它表示锁不可迭代。我认为一定有一种方法,因为 python 中的对象是通过引用传递的,所以如果我可以迭代一个总是为我提供对同一锁的引用的对象,这可能会起作用。但要怎么做呢?

python multithreading concurrency mutex
1个回答
0
投票

您可以将锁定设置为全局,但为了回答您的问题,我建议:

from threading import Lock
from concurrent.futures import ThreadPoolExecutor
from itertools import repeat

def thread_function(number: int, lock: Lock):
    with lock:
        print("Hello from the thread with argument: ", number)

def main():
    lock = Lock()
    with ThreadPoolExecutor(max_workers=10) as executor:
        executor.map(thread_function, range(10), repeat(lock))

if __name__ == '__main__':
    main()
© www.soinside.com 2019 - 2024. All rights reserved.