threading.Condition

2019-01-24  本文已影响2人  ThomasYoungK
"""https://www.bogotobogo.com/python/Multithread/python_multithreading_Synchronization_Condition_Objects_Producer_Consumer.php
"""

import threading
import time
import logging

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


def consumer(cv):
    logging.debug('Consumer thread started ...')
    with cv:  # 获得锁
        logging.debug('Consumer waiting ...')
        cv.wait()  # 未苏醒时释放锁并卡住,被唤醒后抢占锁并继续执行, 否则继续卡在这里等待锁释放
        logging.debug('Consumer consumed the resource')
        time.sleep(2)
    # 释放锁


def producer(cv):
    logging.debug('Producer thread started ...')
    with cv:  # 获得锁
        logging.debug('Making resource available')
        logging.debug('Notifying to all consumers')
        cv.notifyAll()
        logging.debug('wating 2 seconds then release lock')
        time.sleep(2)
    # 释放锁


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

    cs1.start()
    time.sleep(2)
    cs2.start()
    time.sleep(2)
    pd.start()
    cs1.join()
    cs2.join()
    pd.join()
    logging.debug('end')

上一篇下一篇

猜你喜欢

热点阅读