. Advertisement .
. Advertisement .
Do you know what Python mutex is and what it is for? It is okay if you don’t, as this module can be quite complicated, especially for beginners. This guide will explain everything about Python mutex, making it easier for you to understand.
What Is Python Mutex?
Mutex stands for mutual exclusion, indicating that only one single thread can make use of a specific resource at a provided moment. Mutex prevents many threads from using a specific resource at once in a single program. The other threads are locked, and their access to the crucial area is limited.
In case you don’t know what a thread is, it is a unique execution flow. This implies that there will be two simultaneous events in your program. However, the majority of Python 3 implementations only give the impression that the several threads are running concurrently when they actually don’t.
How Python Mutex Works
In Python, the module threading’s
lock() feature can be used to lock threads as part of mutex implementation. When the second thread is ready to end, it will hold off until the first one finishes.
To achieve this, you must use the second thread and force it to wait till the first one is finished. Once the first one is finished, the second thread’s lock may be released.
Observe the code below to understand better.
import threading, time, random
mutex = threading.Lock() class thread_one(threading.Thread): def run(self): global mutex print ("The first thread is now sleeping") time.sleep(random.randint(1, 5)) print("First thread is finished") mutex.release() class thread_two(threading.Thread): def run(self): global mutex print ("The second thread is now sleeping") time.sleep(random.randint(1, 5)) mutex.acquire() print("Second thread is finished")
mutex.acquire() t1 = thread_one() t2 = thread_two() t1.start() t2.start()
The first thread is now sleeping The second thread is now sleeping First thread is finished Second thread is finished
The second thread in the example above is not unlocked till the first one is finished. It will hold open the lock while it awaits the first thread. As you can see, the keyword global is utilized in the sample code since both threads employ this keyword.
For those who don’t know, the keyword global can construct global variables and modify existing variables in local contexts. Keep in mind that the statement print follows the statement acquire rather than coming before it since the thread is still waiting and is not yet finished.
Thus, locking the threads is crucial. If both threads concurrently share one resource, it could cause the application to crash.
The Bottom Line
Above are the basics of Python mutex. This mechanism is very useful in computer science, so make sure you spend time getting to know it as well as how to utilize it properly.Bonus: If you want to gain more skills in Python, we can also provide guides on importing CSV files, creating Pandas DataFrame, and many more.