038信号量
2018-06-18 01:47:27来源:未知 阅读 ()
步骤: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()
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
下一篇:批量自动重命名音乐文件
- Python3安装impala 2019-08-13
- 网络编程之udp_socket 2019-07-24
- xadmin进行全局配置(修改模块名为中文以及其他自定义的操作 2019-07-24
- Django中信号signals简单使用 2019-07-24
- Python 建模步骤 2019-05-23
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash