Imagine I have two threads, each modifying a different variable. Can I pass the same lock object to them, or shall I use two separate locks? In general, when shall I use multiple locks?
Here is a toy example:
from threading import Thread, Lock
from time import sleep
def task(lock, var):
with lock:
var = 1
sleep(5)
lock = Lock()
var1 = []
var2 = []
Thread(target=task, args=(lock, var1)).start()
Thread(target=task, args=(lock, var2)).start()
or is it better
lock1 = Lock()
lock2 = Lock()
var1 = []
var2 = []
Thread(target=task, args=(lock1, var1)).start()
Thread(target=task, args=(lock2, var2)).start()
>Solution :
Only one thread can hold a lock at a time, and a lock is used to provide mutually-exclusive access to a piece of data (or variable).
Based on your example, where each thread accesses separate variables, you want two separate locks—one per variable. Note that if only one thread accesses a variable, though, you do not need to use a lock for it.
If you were to only use one lock, only one thread would be able to perform "work" at a time—even though their work is completely independent.