【pyhton编程】条件变量Condition

条件变量Condition

函数作用说明:

函数 作用
acquire 线程锁,注意线程条件变量 Condition 中的所有相关函数使用必须在acquire/release内部操作;
release  释放锁,注意线程条件变量 Condition 中的所有相关函数使用必须在acquire/release内部操作;
wait( timeout ) 线程挂起(阻塞状态),直到收到一个 notify 通知或者超时才会被唤醒继续运行(超时参数默认不设置,可选填,类型是浮点数,单位是秒)。wait 必须在已获得 Lock 前提下才能调用,否则会触发 RuntimeError;
notify(n=1)  通知其他线程,那些挂起的线程接到这个通知之后会开始运行,缺省参数,默认是通知一个正等待通知的线程,最多则唤醒 n 个等待的线程。 notify 必须在已获得 Lock 前提下才能调用,否则会触发 RuntimeError ,notify 不会主动释放 Lock ;
notifyAll  如果wait状态线程比较多,notifyAll 的作用就是通知所有线程;

 

1. 例子:

import threading
import time
 
class Producer(threading.Thread):
	def __init__(self):
		threading.Thread.__init__(self)
	
	def run(self):
		global count
		while True:
			con.acquire() 
			if count <20:
				count += 1
				print self.name," Producer product 1,current is %d" %(count)
				con.notify()
			else:
				print self.name,"Producer say box is full"
				con.wait()
			con.release()
			time.sleep(1)
 
class Consumer(threading.Thread):
	def __init__(self):
		threading.Thread.__init__(self)
	
	def run(self):
		global count
		while True:
			con.acquire() 
			if count>4:
				count -=4
				print self.name,"Consumer consume 4,current is %d" %(count)
				con.notify()
			else:
				
				con.wait()
				print self.name," Consumer say box is empty"
			con.release()
			time.sleep(1)
		
		
count = 0
con = threading.Condition()
 
def test():
	for i in range(1):
		a = Consumer()
		a.start()
	
	for i in range(1):
		b =Producer()
		b.start()
	
 
if __name__=='__main__':
	test()

 

参考资料

1. 条件变量 Condition

posted @ 2023-07-07 10:30  苏格拉底的落泪  阅读(39)  评论(0编辑  收藏  举报