步骤:1、新建信号量对象,设置信号量数量
2、线程执行方法中,如果能够获取信号量,则执行,信号量为0不可以获取
1 import threading,time 2 3 class MyThread(threading.Thread): 4 def run(self): 5 if sema.acquire(): 6 print(self.name) 7 time.sleep(0.3) 8 sema.release() 9 10 if __name__ == ‘__main__‘: 11 sema = threading.BoundedSemaphore(5) # sema=threading.Semaphore(5) 12 thrs = [] 13 for i in range(100): 14 thrs.append(MyThread()) 15 for t in thrs: 16 t.start()
例子:
### 强行改的信号量
1 import threading 2 import time 3 class Tickets: 4 def __init__(self): 5 self.ticket = 100 6 7 def sell_ticket(self): 8 while self.ticket > 0: 9 if loc.acquire(): 10 print(‘卖出‘,self.ticket,‘票‘,threading.current_thread()) 11 self.ticket -= 1 12 loc.release() 13 time.sleep(0.0001) 14 15 if __name__ == ‘__main__‘: 16 ticket = Tickets() 17 t1 = threading.Thread(target=ticket.sell_ticket) 18 t2 = threading.Thread(target=ticket.sell_ticket) 19 t3 = threading.Thread(target=ticket.sell_ticket) 20 loc = threading.Semaphore(1) 21 t1.start() 22 t2.start() 23 t3.start()
##########38里面多生产多消费信号量实现
1 import time 2 import threading 3 4 class Res: 5 def __init__(self): 6 self.flag = False 7 self.count = 0 8 self.product = ‘‘ 9 10 def set(self,name): 11 lock_con.acquire() 12 while self.flag: 13 lock_con.wait() 14 time.sleep(0.00001) 15 self.count += 1 16 self.product = ‘‘.join([name,‘**‘,str(self.count)]) 17 self.message = ‘‘.join([self.product,‘__生产者__‘,str(threading.current_thread())]) 18 print(self.message) 19 self.flag = True 20 lock_con.notifyAll() 21 lock_con.release() 22 23 def get_product(self): 24 lock_con.acquire() 25 time.sleep(0.00001) 26 while not self.flag: 27 lock_con.wait() 28 self.message = ‘‘.join([self.product,‘__消费者__‘,str(threading.current_thread())]) 29 print(self.message) 30 self.flag = False 31 lock_con.notifyAll() 32 lock_con.release() 33 34 class Producer(threading.Thread): 35 def __init__(self,r): 36 threading.Thread.__init__(self) 37 self.r = r 38 39 def run(self): 40 for i in range(100): 41 self.r.set(‘大白兔奶糖‘) 42 43 class Consumer(threading.Thread): 44 def __init__(self,r): 45 threading.Thread.__init__(self) 46 self.r = r 47 48 def run(self): 49 for i in range(100): 50 self.r.get_product() 51 52 if __name__ == ‘__main__‘: 53 lock_con = threading.Condition() 54 r = Res() 55 l = [] 56 for i in range(5): 57 l.append(Consumer(r)) 58 for i in range(5): 59 l.append(Producer(r)) 60 for a in l: 61 a.start()