27 python 初學(信號量、條件變量、同步條件、隊列)
阿新 • • 發佈:2019-01-30
sta 訪問共享 def list 意思 線程 .cn pla com
參考博客: www.cnblogs.com/yuanchenqi/articles/5733873.html
semaphore 信號量:
condition 條件變量:
event 同步條件:條件同步和條件變量同步差不多意思,只是少了鎖功能。因為條件同步設計於別訪問共享資源的條件環境
多線程利器(queue):隊列本身有一把鎖
q.put(‘xiaoming’, 0)
q.get(0)
q.qsize() 返回隊列大小
q.empty()
q.full()
semaphore:
# _author: lily # _date: 2019/1/29 import threading , timeView Codeclass MyThread(threading.Thread): def run(self): if semaphore.acquire(): print(self.name) time.sleep(3) semaphore.release() if __name__ == ‘__main__‘: semaphore = threading.BoundedSemaphore(5) thread_list = [] for i in range(100): thread_list.append(MyThread())for i in thread_list: i.start()
condition:
# _author: lily # _date: 2019/1/29 import threading,time from random import randint class Producer(threading.Thread): def run(self): global L while True: val = randint(0, 100) print(‘Producer‘, self.name, ‘View Code: Append‘, str(val), L) if lock_con.acquire(): L.append(val) lock_con.notify() lock_con.release() time.sleep(3) class Consumer(threading.Thread): def run(self): global L while True: lock_con.acquire() if len(L) == 0: lock_con.wait() print(‘Consumer‘, self.name, ‘: Delete‘, str(L[0]), L) del L[0] lock_con.release() time.sleep(0.25) if __name__ == ‘__main__‘: L = [] lock_con = threading.Condition() threads = [] for i in range(5): threads.append(Producer()) threads.append(Consumer()) for t in threads: t.start() for t in threads: t.join()
queue:
# _author: lily # _date: 2019/1/30 import queue # q = queue.Queue() q = queue.Queue(3) # 設置隊列大小 q.put(‘xiaoming‘, 0) q.put(‘xiaohong‘) q.put(‘xiaofang‘, 0) # 隊列大小為 2 ,當要放置第三個數據的時候,1會被阻塞,0會報錯。默認參數為1 print(q.get()) print(q.get()) print(q.get()) print(q.get(0)) # 參數為 0 的時候如果隊列空了,還去取值,就會報錯。參數為 1 會被阻塞View Code
27 python 初學(信號量、條件變量、同步條件、隊列)