educative.io

Why can't there be any race condition scenario here where one of the two child thread and main thread tries to acquire condition at same time?

from threading import Condition
from threading import Thread
from threading import current_thread

flag = False

cond_var = Condition()

def child_task():
global flag
name = current_thread().getName()

cond_var.acquire()
if not flag:
    cond_var.wait()
    print("\n{0} woken up \n".format(name))

flag = False
cond_var.release()

print("\n{0} exiting\n".format(name))

thread1 = Thread(target=child_task, name=“thread1”)
thread2 = Thread(target=child_task, name=“thread2”)

thread1.start()
thread2.start()

cond_var.acquire()
cond_var.notify_all()
cond_var.release()

thread1.join()
thread2.join()

print(“main thread exits”)

Hi @Fenil !!
This is because the Condition object cond_var is acquired by the main thread before notifying all threads, and it is released after the notification. Therefore, when the child threads wake up from their wait state, they will acquire the condition one by one.

Here’s a step-by-step explanation of the code execution:

  1. The main thread acquires the cond_var condition.
  2. The main thread notifies all threads (child threads) waiting on cond_var.
  3. The main thread releases the cond_var condition.
  4. Child threads wake up one by one, and each acquires the cond_var condition before proceeding.
  5. Child threads print their respective messages and release the cond_var condition.
  6. The child threads join, and the main thread waits for their completion.
  7. The main thread prints “main thread exits” and terminates.

Due to the sequential nature of the thread execution and the proper usage of the Condition object, there is no opportunity for a race condition to occur in this code.
I hope it helps. Happy learning :blush:

1 Like