信号量适用与多线程竞争有限资源的情况。

 from atexit import register
from time import ctime, sleep
from threading import Thread, Lock, BoundedSemaphore
from random import randrange lock = Lock()
MAX = 5 #信号量大小
candytray = BoundedSemaphore(MAX) def refull():
with lock:
print('refulling...')
try:
candytray.release()
except ValueError:
print('Is Full!')
else:
print('OK') def buy():
with lock:
print('buying...')
if candytray.acquire(False): #加入False参数,如果信号量为空,则不阻塞,而是返回错误,感觉类似与C语言中的pthread_mutex_trylock
print('OK')
else:
print('empty') def consumer(loops):
for i in range(loops):
refull()
sleep(randrange(3)) #睡眠时间尽量长于creater的概率尽量大, def creater(loops):
for i in range(loops):
buy()
sleep(randrange(5)) def main():
print('starting...')
n = randrange(2,6)
print('the candy mechine full with {0}'.format(MAX))
Thread(target=creater,args=(randrange(n,n+MAX+2),)).start()
Thread(target=consumer, args=(randrange(n,n+MAX+2),)).start() @register
def atexitt():
print('The end!') if __name__ == '__main__':
main()

输出结果:

参考资料:Python核心编程.第四章.Wesley Chun著

【Python@Thread】Semaphore&糖果机的更多相关文章

  1. TLS 与 python thread local

    TLS 先说TLS( Thread Local Storage),wiki上是这么解释的: Thread-local storage (TLS) is a computer programming m ...

  2. Python thread local

    由于GIL的原因,笔者在日常开发中几乎没有用到python的多线程.如果需要并发,一般使用多进程,对于IO Bound这种情况,使用协程也是不错的注意.但是在python很多的网络库中,都支持多线程, ...

  3. python lock, semaphore, event实现线程同步

    lock 机制不管你是java, C#, 还是python都是常用的线程同步机制, 相比较C# 的锁机制, python的加锁显得比较简单, 直接调用threading 标准库的lock 就可以了. ...

  4. [Python 多线程] Semaphore、BounedeSemaphore (十二)

    Semaphore 信号量,信号量对象内部维护一个倒计数器,每一次acquire都会减1,当acquire方法发现计数为0就阻塞请求的线程,直到其它线程对信号量release后,计数大于0,恢复阻塞的 ...

  5. Python之路——堡垒机原理及其简单实现

    1 堡垒机基本概述 其从功能上讲,它综合了核心系统运维和安全审计管控两大主干功能,从技术实现上讲,通过切断终端计算机对网络和服务器资源的直接访问,而采用协议代理的方式,接管了终端计算机对网络和服务器的 ...

  6. python之路 堡垒机paramiko

    paramiko 1.安装 pip3 install paramiko 二.使用 SSHClient 用于连接远程服务器并执行基本命令 基于用户名密码连接: import paramiko # 创建S ...

  7. Python thread (线程)

    线程 (thread) 操作系统最小的调度单位,是一串指令的集合 程序一开始就有一个主线程,新启动的线程和主线程之间互不影响,主线程启动子线程之后就相互独立(子线程也可以启动线程),无论子线程是否执行 ...

  8. Python Thread related

    1.Thread.join([timeout]) Wait until the thread terminates. This blocks the calling thread until the ...

  9. python thread的join方法解释

    python的Thread类中提供了join()方法,使得一个线程可以等待另一个线程执行结束后再继续运行.这个方法还可以设定一个timeout参数,避免无休止的等待.因为两个线程顺序完成,看起来象一个 ...

随机推荐

  1. css学习笔记1

    :before,:after伪元素 伪元素特性(目前已经遇到的) 它不存在于文档中,所以js无法操作它 它属于主元素本身,有些伪类仅仅是代表元素内容的一部分,譬如:first-letter代表第一个字 ...

  2. yeoman生成react基本架构

    工欲善其事必先利其器.在开始react开始之前,我们先使用一系列的前段工具构建自己的前端集成解决方案. 环境配置: Bower,node js,npm,Grunt,Gulp,Yeoman 作者一直使用 ...

  3. Girl Develop It Chapter Leaders at 2015 Annual Leadership Summit

    Girl Develop It Chapter Leaders at 2015 Annual Leadership Summit Corinne Warnshuis, Executive Direct ...

  4. C# EnumHelper

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection ...

  5. html css jquery 回到顶部按钮

    今天做了个回到顶部的功能,在这里记录一下,有需要可以拿去试试! CSS部分,很简单就一个class /*回到顶部*/ .back-top { position: fixed; right: 15px; ...

  6. Hibernate——脏检查和缓存清理机制

    Session到底是如何进行脏检查的呢? 当一个Customer对象被加入到Session缓存中时,Session会为Customer对象的值类型的属性复制一份快照.当Session清理缓存时,会先进 ...

  7. POJ 2761 Feed the dogs

    主席树,区间第$k$大. #pragma comment(linker, "/STACK:1024000000,1024000000") #include<cstdio> ...

  8. JQuery-常用小组件

    常用的小组件记录 1. 单选框.复选框重置样式效果 参考: http://www.cnblogs.com/sanshi/p/4369375.html 三生石上 参考: http://www.jq22. ...

  9. [河南省ACM省赛-第四届] 序号互换 (nyoj 303)

    相似与27进制的转换 #include<iostream> #include<cstdio> #include<cstring> #include<strin ...

  10. AngularJS 初学笔记(理论基础)

    AngularJS 是一个 JavaScript 框架.它是一个以 JavaScript 编写的库. AngularJS 通过 ng-directives 扩展了 HTML. ng-app 指令定义一 ...