简体   繁体   English

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

[英]Python - Multithreading - Does Lock have to be global?

I am beginner of multithreading in python. 我是python中多线程的初学者。
I want to use a Lock in threads. 我想在线程中使用Lock。 Does it have to be declared global in the thread? 是否必须在线程中声明为全局? My code looks like this: 我的代码看起来像这样:

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()

No, it does not have to be global. 不,它不一定是全球性的。 You can create it in a function and then pass it to your threads as an argument like so: 您可以在函数中创建它,然后将其作为参数传递给您的线程,如下所示:

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()

To answer your direct question, no global does not have to be used for the thread to know what the lock variable is. 要回答你的直接问题,线程不必使用global来知道锁变量是什么。 Here is more information on scope in Python 以下是有关Python范围的更多信息

Unfortunately, the answer to "the correct usage" depends on your application/situation. 不幸的是,“正确使用”的答案取决于您的应用/情况。 There is nothing inherently wrong with what you're doing as long as your lock is actually global to your application. 只要您的锁实际上是应用程序的全局锁定,您所做的事情就没有任何内在错误。 If your lock is not global to your application or if you want to break your application apart, you may do so by creating your own thread objects. 如果您的锁不是您的应用程序的全局锁,或者您想要破坏您的应用程序,您可以通过创建自己的线程对象来实现。 Here is a great tutorial on using threads/locks. 这是一个关于使用线程/锁的好教程。

Good Luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM