gpt4 book ai didi

Python - 多线程 - Lock 必须是全局的吗?

转载 作者:太空狗 更新时间:2023-10-30 00:16:45 25 4
gpt4 key购买 nike

我是 python 多线程的初学者。
我想在线程中使用锁。是否必须在线程中声明为全局的?我的代码如下所示:

i = 0
lock = threading.RLock()
def do_work():
global i
# global lock ?????????????
while i < len(my_list):
lock.acquire()
my_i = i
i += 1
lock.release()
my_list[my_i].some_works()

workers = [threading.Thread(target=do_work) for _ in range(8)]
for worker in workers:
worker.start()

最佳答案

不,它不必是全局的。您可以在函数中创建它,然后将其作为参数传递给您的线程,如下所示:

i = 0

def do_work(lock):
global i

while i < len(my_list):
with lock: # cleaner way to .acquire() and .release()
my_i = i
i += 1
my_list[my_i].some_works()

def main():
lock = threading.RLock()

workers = [threading.Thread(target=do_work, args=lock,) for _ in range(8)]
for worker in workers:
worker.start()

main()

关于Python - 多线程 - Lock 必须是全局的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35340493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com