Analysis of Python thread condition variable condition principle

Time:2020-5-19

This article mainly introduces the principle analysis of Python thread condition variable condition. The example code is introduced in detail in this article, which has certain reference value for your study or work. You can refer to the following for your friends

The condition object is a conditional variable, which is always associated with some kind of lock. It can be an external incoming lock or a lock created by the system by default. When several conditional variables share a lock, you should pass in a lock yourself. You don’t need to worry about this lock. The condition class will manage it.

Acquire () and release () can manipulate the associated lock. Other methods must be used when the lock is locked. Wait () will release the lock and block the thread until it is woken up by another thread through notify () or notify all(). Once awakened, the lock is locked by wait().

The code example of the classic consumer / producer problem is:


import threading
import time
import logging

logging.basicConfig(level=logging.DEBUG,
          format='(%(threadName)-9s) %(message)s',)

def consumer(cv):
  logging.debug('Consumer thread started ...')
  with cv:
    logging.debug('Consumer waiting ...')
    cv.acquire()
    cv.wait()
    logging.debug('Consumer consumed the resource')
    cv.release()

def producer(cv):
  logging.debug('Producer thread started ...')
  with cv:
    cv.acquire()
    logging.debug('Making resource available')
    logging.debug('Notifying to all consumers')
    cv.notify()
    cv.release()

if __name__ == '__main__':
  condition = threading.Condition()
  cs1 = threading.Thread(name='consumer1', target=consumer, args=(condition,))
  #cs2 = threading.Thread(name='consumer2', target=consumer, args=(condition,state))
  pd = threading.Thread(name='producer', target=producer, args=(condition,))

  cs1.start()
  time.sleep(2)
  #cs2.start()
  #time.sleep(2)
  pd.start()

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.