import threading import logging import time logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s [%(threadName)s] %(message)s') class Message: def __init__(self, message): self.message = message def consumer(cond, message): with cond: cond.wait() logging.debug("consumer {0}".format(message.message)) def producer(cond, message): with cond: print('====') time.sleep(2) message.message = 'ha ha ha ' logging.debug("producer {0}".format(message.message)) cond.notify_all() if __name__ == '__main__': message = Message(None) cond = threading.Condition() c1 = threading.Thread(target=consumer, args=(cond, message), name="consumer-1") c1.start() c2 = threading.Thread(target=consumer, args=(cond, message), name="consumer-2") c2.start() p = threading.Thread(target=producer, args=(cond, message), name="producer") p.start()
上边的测试代码中定义了一个producer方法用于生产数据,consumer方法用于消费数据,当运行上边代码后,先是输出了====,再等待2秒后输出了2016-08-21 17:29:16,212 DEBUG [producer] producer ha ha ha ,接着跟着输出了2016-08-21 17:29:16,212 DEBUG [consumer-1] consumer ha ha ha和2016-08-21 17:29:16,212 DEBUG [consumer-2] consumer ha ha ha,如下所示:
1 2 3 4
==== 2016-08-21 17:29:16,212 DEBUG [producer] producer ha ha ha 2016-08-21 17:29:16,212 DEBUG [consumer-1] consumer ha ha ha 2016-08-21 17:29:16,212 DEBUG [consumer-2] consumer ha ha ha