速記:python多線程之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,執行完畢。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章