
察布查尔锡伯网站制作公司哪家好,找创新互联!从网页设计、网站建设、微信开发、APP开发、响应式网站等网站项目制作,到程序开发,运营维护。创新互联2013年至今到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选创新互联。
条件变量同步
有一类线程需要满足条件之后才能够继续执行,python提供了threading.Condition 对象用于条件变量线程的支持,它除了能提供RLock()或Lock()的方法外,还提供了 wait()、notify()、notifyAll()方法。
lock_con=threading.Condition([Lock/Rlock]): 锁是可选选项,不传人锁,对象自动创建一个RLock()。
wait():条件不满足时调用,线程会释放锁并进入等待阻塞;
notify():条件创造后调用,通知等待池激活一个线程;
notifyAll():条件创造后调用,通知等待池激活所有线程。
相关推荐:《Python视频教程》
import threading, time
from random import randint
class Producer(threading.Thread):
def run(self):
global L
while True:
val = randint(0, 100)
print('生产者', self.name, ':Append'+str(val),L)
if lock_con.acquire():
L.append(val)
lock_con.notify()
lock_con.release()
time.sleep(3)
class Consumer(threading.Thread):
def run(self):
global L
while True:
lock_con.acquire()
if len(L) == 0:
lock_con.wait()
print('消费者', self.name, ":Delete" + str(L[0]), L)
del L[0]
lock_con.release()
time.sleep(0.25)
if __name__ == "__main__":
L = []
lock_con = threading.Condition()
threads = []
for i in range(5):
threads.append(Producer())
threads.append(Consumer())
for t in threads:
t.start()
for t in threads:
t.join()
print('---- end ----')运行结果:
生产者 Thread-1 :Append63 [] 生产者 Thread-2 :Append66 [63] 生产者 Thread-3 :Append20 [63, 66] 生产者 Thread-4 :Append83 [63, 66, 20] 生产者 Thread-5 :Append2 [63, 66, 20, 83] 生产者 Thread-4 :Append26 [] 消费者 Thread-6 :Delete26 [26] 生产者 Thread-2 :Append21 [] 生产者 Thread-3 :Append71 [21] 生产者 Thread-1 :Append19 [21, 71] 生产者 Thread-5 :Append100 [21, 71, 19] 生产者 Thread-1 :Append96 [] 消费者 Thread-6 :Delete96 [96] ........
分享题目:创新互联Python教程:Python如何实现条件变量同步
文章地址:http://www.csdahua.cn/qtweb/news49/395249.html
网站建设、网络推广公司-快上网,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 快上网