pythonスレッドの条件変数Conditionの使用例

1535 ワード

Conditionオブジェクトは、常に何らかのロックに関連付けられた条件変数であり、外部から送信されたロックやシステムのデフォルトで作成されたロックであってもよい.いくつかの条件変数がロックを共有する場合は、自分でロックを入力する必要があります.このロックは心配する必要はありません.Conditionクラスが管理します.
acquire()とrelease()は、この関連するロックを操作できます.他の方法は、このロックがロックされている場合に使用する必要があります.wait()はこのロックを解放し、他のスレッドがnotify()またはnotify_を通過するまでスレッドをブロックします.all()で起こします.いったん目が覚めると、この鍵はまたwait()にロックされます.
古典的なconsumer/producer問題のコード例は、次のとおりです.
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()