Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I use the same lock on multiple threads if they do not access the same variable?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading