threading_condition_demo

 1 import threading, time
 2 
 3 share = 0
 4 cond = threading.Condition()
 5 
 6 """
 7 生产者与消费者
 8 """
 9 
10 
11 class ProThread(threading.Thread):
12     def __init__(self):
13         super().__init__()
14         self.name = 'Produce'
15 
16     def run(self):
17         # global 表示全局变量
18         global share
19         if cond.acquire():
20             while True:
21                 if not share:
22                     share += 1
23                     print(self.name, share)
24                     '''
25                      唤醒在此条件下等待的一个或多个线程(如果有的话)。如果调用线程在此方法时没有获得锁被调用时,会引发一个运行时错误。
26                      最多唤醒n个等待条件的线程变量;如果没有线程在等待,那么这是一个no-op。    
27                   '''
28                     cond.notify()
29                 '''
30                   如果调用线程在此方法时没有获得锁被调用时,会引发一个运行时错误。
31                   这个方法释放底层锁,然后阻塞,直到它释放由notify()或notify_all()调用来唤醒相同的条件变量在另一个线程,或直到可选超时发生。
32                   一次唤醒或超时,它重新获得锁并返回。
33               '''
34                 cond.wait()
35                 time.sleep(1)
36 
37 
38 class CusThread(threading.Thread):
39     def __init__(self):
40         super().__init__()
41         self.name = 'Custom'
42 
43     def run(self):
44         global share
45         if cond.acquire():
46             while True:
47                 if share:
48                     share -= 1
49                     print(self.name, share)
50 
51                     cond.notify()
52 
53                 cond.wait()
54                 time.sleep(1)
55 
56 
57 if __name__ == '__main__':
58     pro = ProThread()
59     cus = CusThread()
60     pro.start()
61     cus.start()

 

posted on 2018-08-15 01:14  jovelove  阅读(193)  评论(0)    收藏  举报