Harish Rudroju
Harish Rudroju

Reputation: 51

Inter Thread Communication in Python using Condition object

I have written following code as a part of practicing inter thread communication in python using 'Condition' object

from threading import *
import time
c=Condition()

def sum():
    time.sleep(2)#if i comment this line then pgm waits,only sum() fun print stmt is executed
    c.acquire()
    print('here after this stms notify is called')
    c.notify()
    c.release()

def display():
    c.acquire()
    c.wait()
    print('display print is executing after notify')
    c.notify()
    c.release()

def show():
    c.acquire()
    c.wait()
    print('show print is executing after notify')
    c.release()

t2=Thread(target=display)
t3=Thread(target=show)
t1=Thread(target=sum)
t1.start()
t2.start()
t3.start()

the pgm works fine but if i comment time.sleep(2) in sum() function then only print stmt of sum() function is executed and then waits. please tell me why this happens and why does this time.sleep(2) line really makes this difference

Upvotes: 1

Views: 1701

Answers (1)

Steve
Steve

Reputation: 7271

The wait method waits for another thread to awaken it by calling notify. This means we must call wait on threads before a call to notify. What is happening is that sum with the sleep allows the display and show threads to call wait. At which point when the sum function calls notify one of them is woken up and can be called.

When the time.sleep(2) is not in the sum function, the sum function is acquiring c and running to completion before the display or show functions can get into the wait state. Note that this is a race condition, and it is feasible that on some occasions it might work as you want.

Also, by missing out the call to notify in the show method there is another potential race condition that means the display function is not called. This is because notify will wake up one thread by default. So this will only complete if the thread running display is woken up first.

In response to your comment about the difference between events and conditions. An event is a lightweight way of communicating between threads. One thread can signal an event and any number of threads can wait for the event. When the event is signalled all of the threads will wake up and execute. There is no lock involved. Events are typically not enough to protect state shared between threads.

With a condition variable a lock is used which means only one thread waiting on the condition variable is able to acquire the lock. This is good for protecting shared state.

Upvotes: 3

Related Questions