简体   繁体   中英

Python - Multithreading - Does Lock have to be global?

I am beginner of multithreading in python.
I want to use a Lock in threads. 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. Here is more information on scope in 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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