首页 > 代码库 > 【Python@Thread】Semaphore&糖果机
【Python@Thread】Semaphore&糖果机
信号量适用与多线程竞争有限资源的情况。
1 from atexit import register 2 from time import ctime, sleep 3 from threading import Thread, Lock, BoundedSemaphore 4 from random import randrange 5 6 lock = Lock() 7 MAX = 5 #信号量大小 8 candytray = BoundedSemaphore(MAX) 9 10 11 def refull(): 12 with lock: 13 print(‘refulling...‘) 14 try: 15 candytray.release() 16 except ValueError: 17 print(‘Is Full!‘) 18 else: 19 print(‘OK‘) 20 21 def buy(): 22 with lock: 23 print(‘buying...‘) 24 if candytray.acquire(False): #加入False参数,如果信号量为空,则不阻塞,而是返回错误,感觉类似与C语言中的pthread_mutex_trylock 25 print(‘OK‘) 26 else: 27 print(‘empty‘) 28 29 def consumer(loops): 30 for i in range(loops): 31 refull() 32 sleep(randrange(3)) #睡眠时间尽量长于creater的概率尽量大, 33 34 35 def creater(loops): 36 for i in range(loops): 37 buy() 38 sleep(randrange(5)) 39 40 41 def main(): 42 print(‘starting...‘) 43 n = randrange(2,6) 44 print(‘the candy mechine full with {0}‘.format(MAX)) 45 Thread(target=creater,args=(randrange(n,n+MAX+2),)).start() 46 Thread(target=consumer, args=(randrange(n,n+MAX+2),)).start() 47 48 49 @register 50 def atexitt(): 51 print(‘The end!‘) 52 53 54 if __name__ == ‘__main__‘: 55 main()
输出结果:
参考资料:Python核心编程.第四章.Wesley Chun著
【Python@Thread】Semaphore&糖果机
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。