python模块学习(threading模块中的Semaphore类和BoundedSemaphore类)
来源:互联网 发布:mac只安装win10分区 编辑:程序博客网 时间:2024/05/19 22:47
学习版本3.5.2
Semaphore类和BoundedSemaphore类都是信号量类,每次有线程获得信号量的时候(即acquire())计数器-1,释放信号量时候(release())计数器+1,计数器为0的时候其它线程就被阻塞无法获得信号量。当计数器为设定好的上限的时候BoundedSemaphore就无法进行release()操作了,Semaphore没有这个限制检查。
#/usr/bin/python3# -*- utf-8 -*-#学习版本3.5.2import threadingimport timenum = 2def test(): global num n = se.acquire() num -= 1 print("Semaphore acquire:",num) time.sleep(1) se.release() num += 1 print("Semaphore release:",num)if __name__ == "__main__": se = threading.BoundedSemaphore(num) tlist = [] for i in range(5): t = threading.Thread(target=test) tlist.append(t) for i in tlist: i.start() print("main")
运行结果
Semaphore acquire: 1Semaphore acquire: 0mainSemaphore release: 1Semaphore release: 2Semaphore acquire: 1Semaphore acquire: 0Semaphore release: 1Semaphore release: 2Semaphore acquire: 1Semaphore release: 2
当使用Semaphore时候,可以直接调用release()使得内置的计数器就直接加1,BoundedSemaphore这样的操作就会抛出ValueError。
#/usr/bin/python3# -*- utf-8 -*-#学习版本3.5.2import threadingimport timenum = 2def test(): global num n = se.acquire() num -= 1 print("Semaphore acquire:",num) time.sleep(1) se.release() num += 1 print("Semaphore release:",num)if __name__ == "__main__": se = threading.Semaphore(num) se.release() tlist = [] for i in range(5): t = threading.Thread(target=test) tlist.append(t) for i in tlist: i.start() print("main")
运行结果就是3个线程3个线程一起跑,就像threading.Semaphore(3)的效果一样
Semaphore acquire: 1Semaphore acquire: 0Semaphore acquire: -1mainSemaphore release: 0Semaphore release: 1Semaphore acquire: 1Semaphore release: 2Semaphore acquire: 0Semaphore release: 1Semaphore release: 2
阅读全文
0 0
- python模块学习(threading模块中的Semaphore类和BoundedSemaphore类)
- python—threading.Semaphore和BoundedSemaphore【threading模块介绍04】
- 关于Python的进程线程协程之threading模块(二)Lock,RLock对象以及Semaphore,BoundedSemaphore对象
- python模块学习(threading模块中的Thread类)
- python模块学习(threading模块中的Timer类)
- python模块学习(threading模块中的Condition类)
- python模块学习(threading模块中的Event类)
- python模块学习(threading模块中的Barrier类)
- python模块学习(threading模块中的Lock类和RLock类)
- python中的threading模块
- python多线程threading使用Semaphore或BoundedSemaphore实现并发限制
- python多线程模块threading学习
- python模块学习(threading模块的方法)
- python的threading模块中threading.RLock和threading.Lock
- Python 多线程(threading模块)
- Python 多线程(threading模块)
- Python多线程(threading模块)
- Python模块学习 ---- threading 多线程控制和处理
- 回调函数&&回调机制
- Spring Boot 属性配置和使用
- MapReduce类的输入文件的格式
- 《js高级程序设计》--函数
- 【比特币】BIP-0021 详细说明
- python模块学习(threading模块中的Semaphore类和BoundedSemaphore类)
- 深度学习-LSTM网络-代码示例
- learn opencv-选择性搜索对象检测(C ++ / Python)
- oracle数据库(PL/SQL)
- Unity 5 中的全局光照技术详解(建议收藏)
- No gulpfile found的解决办法
- sql选择最低的平均工资
- <每日一题>二分搜索
- Cookie的作用域