Mutex in python

Mutex means Mutual Exclusion. It means that at a given specific time, only one thread can use a particular resource. If one program has multi-threads, then mutual exclusion restricts the threads to use that particular resource simultaneously. It locks the other threads and restricts their entry into the critical section.

This tutorial will demonstrate the use of mutex in Python.

To implement mutex in Python, we can use the lock() function from the threading module to lock the threads. If the second thread is about to finish before the first thread, it will wait for the first thread to finish. We lock the second thread to ensure this, and then we make it wait for the first thread to finish. And when the first thread is done, we release the lock of the second thread.

See the code given below.

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")
class thread_two(threading.Thread):
	def run(self):
		global mutex
		print ("The second thread is now sleeping")
		time.sleep(random.randint(1, 5))
		print("Second thread is finished")
t1 = thread_one()
t2 = thread_two()


The first thread is now sleeping
The second thread is now sleeping
First thread is finished
Second thread is finished

In this code, the second thread is not released until the first thread is done. The second thread waits for the first thread in the lock. The global keyword is used in the code because both the thread uses it. Note that the print statement comes right after the acquire statement, not before, because as long as the thread is waiting, it has not finished yet.

Therefore, it is very important to lock the threads. Otherwise, it may crash the application if two threads share the same resource simultaneously.

DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.