Python - multithreading - should Lock be global?

I am starting multithreading in python.
I want to use Lock in threads. Should it be declared global in the stream? My code is as follows:

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()
+6
source share
2 answers

No, it should not be global. You can create it in a function and then pass it to your threads as an argument as follows:

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()
+1
source

To answer your direct question, you do not need to use a globalthread to find out what a blocking variable is. Here is more area info in Python

, " " /. , , . , , . /.

!

0

Source: https://habr.com/ru/post/1628309/


All Articles