速记:threading.Condition

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 ...')
    global a
    if a != 1:
        with cv:  # 获得锁
            logging.debug('Consumer waiting ...')
            cv.wait()  # 未苏醒时释放锁并卡住,被唤醒后抢占锁并继续执行, 否则继续卡在这里等待锁释放
            logging.debug('Consumer consumed the resource')
            time.sleep(2)
    # 释放锁

def consumer2(cv):
    logging.debug('Consumer thread started ...')
    global a
    if a == 1:
        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 ...')
    global a
    if a==1:
        with cv:  # 获得锁
            logging.debug('Making resource available')
            logging.debug('Notifying to one consumers')
            cv.notify()
            logging.debug('wating 2 seconds then release lock')
            time.sleep(2)
    # 释放锁


if __name__ == '__main__':
    a = 1
    condition = threading.Condition()  # condition内部有把锁
    cs1 = threading.Thread(name='consumer1', target=consumer, args=(condition,))
    cs2 = threading.Thread(name='consumer2', target=consumer2, 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')

结果:

(consumer1) 2020-01-15 23:35:51,389 Consumer thread started ...
(consumer2) 2020-01-15 23:35:53,391 Consumer thread started ...
(consumer2) 2020-01-15 23:35:53,391 Consumer waiting ...
(producer ) 2020-01-15 23:35:55,393 Producer thread started ...
(producer ) 2020-01-15 23:35:55,393 Making resource available
(producer ) 2020-01-15 23:35:55,393 Notifying to all consumers
(producer ) 2020-01-15 23:35:55,393 wating 2 seconds then release lock
(consumer2) 2020-01-15 23:35:57,396 Consumer consumed the resource
(MainThread) 2020-01-15 23:35:59,398 end

两个线程同时运行(python中多线程时假的),consumer1判断为False运行完毕,consumer2判断为True执行wait()语句等待唤醒。producer判断if为True,执行notify()语句唤醒consumer2,执行完毕。

发布了40 篇原创文章 · 获赞 42 · 访问量 3万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 游动-白 设计师: 上身试试

分享到微信朋友圈

×

扫一扫,手机浏览