IKH

Thread Communication

  • Some times threads are required to communicate with each other. This concept is nothing but thread communication or inter thread communication.
  • Example – After producing items producer thread has to communicate with consumer thread to notify about new item. Then consumer thread can consume that new item.
  • In python, we can implement inter thread communication by using the following ways:
    • Event
    • Condition
    • Queue

By using event objects

  • Event object is the simplest communication mechanism between the threads. One thread signals an event and other threads wait for it.

Syntax

Python
eventObj = threading.Event()
  • Event manages an internal flag that can set() or clear()
  • Threads can wait until event set.
  • Methods of Event class:
    • set() ⇒ Internal flag value will become True and it represents GREEN signal for all waiting threads.
    • clear() ⇒ Internal flag value will become False and it represents RED signal for all waiting threads.
    • is_set() ⇒ This method can be used whether the event is set or not.
    • wait()|wait(seconds) ⇒ Thread can wait until event is set.

Example

Python
from threading import *
import time
def producer():
  time.sleep(5)
  print("Producer thread producing items:")
  print("Producer thread giving notification by setting event")
  event.set()
def consumer():
  print("Consumer thread is waiting for updation")
  event.wait()
  print("Consumer thread got notification and consuming items")
event=Event()
t1=Thread(target=producer)
t2=Thread(target=consumer)
t1.start()
t2.start()

Output

PowerShell
Consumer thread is waiting for updation
Producer thread producing items:
Producer thread giving notification by setting event
Consumer thread got notification and consuming items

Example

Python
from threading import *
import time
def trafficpolice():
  while True:
    time.sleep(10)
    print("Traffic Police Giving GREEN Signal")
    event.set()
    time.sleep(20)
    print("Traffic Police Giving RED Signal")
    event.clear()
def driver():
  num=0
  while True:
    print("Drivers waiting for GREEN Signal")
    event.wait()
    print("Traffic Signal is GREEN...Vehicles can move")
    while event.is_set():
      num=num+1
      print("Vehicle No:",num,"Crossing the Signal")
      time.sleep(2)
    print("Traffic Signal is RED...Drivers have to wait")
event=Event()
t1=Thread(target=trafficpolice)
t2=Thread(target=driver)
t1.start()
t2.start()

Output

PowerShell
Drivers waiting for GREEN Signal
Traffic Police Giving GREEN Signal
Traffic Signal is GREEN...Vehicles can move
Vehicle No: 1 Crossing the Signal
Vehicle No: 2 Crossing the Signal
Vehicle No: 3 Crossing the Signal
Vehicle No: 4 Crossing the Signal
Vehicle No: 5 Crossing the Signal
Vehicle No: 6 Crossing the Signal
Vehicle No: 7 Crossing the Signal
Vehicle No: 8 Crossing the Signal
Vehicle No: 9 Crossing the Signal
Vehicle No: 10 Crossing the Signal
Traffic Police Giving RED Signal
Traffic Signal is RED...Drivers have to wait
Drivers waiting for GREEN Signal
Traffic Police Giving GREEN Signal
Traffic Signal is GREEN...Vehicles can move
Vehicle No: 11 Crossing the Signal
Vehicle No: 12 Crossing the Signal
Vehicle No: 13 Crossing the Signal
Vehicle No: 14 Crossing the Signal
Vehicle No: 15 Crossing the Signal
Vehicle No: 16 Crossing the Signal
Vehicle No: 17 Crossing the Signal
Vehicle No: 18 Crossing the Signal
Vehicle No: 19 Crossing the Signal
Vehicle No: 20 Crossing the Signal
Traffic Police Giving RED Signal
Traffic Signal is RED...Drivers have to wait
Drivers waiting for GREEN Signal

By using condition object

  • Condition is the more advanced version of event object for inter thread communication. A condition represents some kind of state change in the application like producing item or consuming item. threads can wait for that condition and threads can be notified once condition happened i.e. condition object allows one or more threads to wait until notified by another thread.
  • Condition is always associated with a RLook.
  • A condition has acquire() and release() methods that call the corresponding methods of the associated lock.

Syntax

Python
conditionObject = threading.Condition()
  • Methods of condition object:
    • acquire() ⇒ To acquire condition object before producing or consuming items i.e. thread acquiring internal lock.
    • release() ⇒ To release condition object after producing or consuming items i.e. thread releases internal lock.
    • wait()|wait(time) ⇒ To wait until getting notification or time expired.
    • notify() ⇒ To give notification for one waiting thread.
    • notifyAll() ⇒ To give notification for all waiting threads.

Example

The producing thread needs to acquire the condition before producing item to the resource and notifying the consumers.

1st Method

Python
from threading import *
def consume(c):
  c.acquire()
  print("Consumer waiting for updation")
  c.wait()
  print("Consumer got notification & consuming the item")
  c.release()
def produce(c):
  c.acquire()
  print("Producer Producing Items")
  print("Producer giving Notification")
  c.notify()
  c.release()
c=Condition()
t1=Thread(target=consume,args=(c,))
t2=Thread(target=produce,args=(c,))
t1.start()
t2.start()

Output

PowerShell
Consumer waiting for updation
Producer Producing Items
Producer giving Notification
Consumer got notification & consuming the item

2nd Method

Python
from threading import *
import time
import random
items=[]
def produce(c):
  while True:
    c.acquire()
    item=random.randint(1,100)
    print("Producer Producing Item:",item)
    items.append(item)
    print("Producer giving Notification")
    c.notify()
    c.release()
    time.sleep(5)
def consume(c):
  while True:
    c.acquire()
    print("Consumer waiting for updation")
    c.wait()
    print("Consumer consumed the item",items.pop())
    c.release()
    time.sleep(5)
c=Condition()
t1=Thread(target=consume,args=(c,))
t2=Thread(target=produce,args=(c,))
t1.start()
t2.start()

Output

PowerShell
Consumer waiting for updation
Producer Producing Item: 17
Producer giving Notification
Consumer consumed the item 17
Producer Producing Item: 59
Producer giving Notification
Consumer waiting for updation
Producer Producing Item: 47
Producer giving Notification
Consumer consumed the item 47
.....
  • In the above program consumer thread expecting updation and hence it is responsible to call wait() method on condition object.
  • Producer thread performing updating and hence it is responsible to call notify() or notifyAll() on condition object.

By using Queue

  • Queues concept is the most enhanced mechanism for inter thread communication and to share data between threads.
  • Queue internally has condition and that condition has Lock. Hence whenever we are using queue we are not required to worry about synchronization.
  • If we want to use queues we should import queue module.

Syntax

Python
import queue
queueObject = queue.Queue()
  • Important methods of queue are:
    • put() ⇒ Put an item into the queue.
    • get() ⇒ Remove and return an item from the queue.
  • Producer thread uses put() method to insert data in the queue. internally this method has logic to acquire the lock before inserting data into queue. after inserting data lock will be released automatically.
  • put() method also checks whether the queue is full or not and if queue is full then the producer thread will entered in to waiting state by calling wait() method internally.
  • Consumer thread uses get() method to remove and get data from the queue. Internally this method has logic to acquire the lock before removing data from the queue. Once removal completed then the lock will be released automatically.
  • If the queue is empty then consumer thread will entered into waiting state by calling wait() method internally. once queue updated with data then the thread will be notified automatically.

Note

  • The queue module takes care of locking for us which is a great advantage.

Example

Python
from threading import *
import time
import random
import queue
def produce(q):
  while True:
    item=random.randint(1,100)
    print("Producer Producing Item:",item)
    q.put(item)
    print("Producer giving Notification")
    time.sleep(5)
def consume(q):
  while True:
    print("Consumer waiting for updation")
    print("Consumer consumed the item:",q.get())
    time.sleep(5)
q=queue.Queue()
t1=Thread(target=consume,args=(q,))
t2=Thread(target=produce,args=(q,))
t1.start()
t2.start()

Output

PowerShell
Consumer waiting for updation
Producer Producing Item: 86
Producer giving Notification
Consumer consumed the item: 86
Consumer waiting for updation
Producer Producing Item: 82
Producer giving Notification
Consumer consumed the item: 82
.....

Types of Queues

  • Python supports 3 types of queues.

FIFO (First In First Out)

  • This is default behavior in which order we put items in the queue, in the same order the items will come out.

Example

Python
import queue
q=queue.Queue()
q.put(10)
q.put(5)
q.put(20)
q.put(15)
while not q.empty():
  print(q.get())

Output

PowerShell
10
5
20
15

LIFO (Last IN First Out)

  • The removal will be happened in the reverse order of insertion.

Example

Python
import queue
q=queue.LifoQueue()
q.put(10)
q.put(5)
q.put(20)
q.put(15)
while not q.empty():
  print(q.get())

Output

PowerShell
15
20
5
10

Priority Queue

  • The elements will be inserted based on some priority order.

Example

Python
import queue
q=queue.PriorityQueue()
q.put(10)
q.put(5)
q.put(20)
q.put(15)
while not q.empty():
  print(q.get())

Output

PowerShell
 5
 10
 15
 20
  • If the data is non-numeric, then we have to provide our data in the form of tuple.
    • (x , y)
    • x is priority.
    • y is our element.

Example

Python
import queue
q=queue.PriorityQueue()
q.put((1,"AAA"))
q.put((3,"CCC"))
q.put((2,"BBB"))
q.put((4,"DDD"))
while not q.empty():
  print(q.get()[1])

Output

PowerShell
AAA
BBB
CCC
DDD

Ungraded Questions

Get ready for an exhilarating evaluation of your understanding! Brace yourself as we dive into the upcoming assessment. Your active participation is key, so make sure to attend and demonstrate your knowledge. Let’s embark on this exciting learning journey together!


Name
Email
Phone

Report an error