python Condition类(锁)
Condition(条件变量)通常与一个锁关联。需要在多个Contidion中共享一个锁时,可以传递一个Lock/RLock实例给构造方法,否则它将自己生成一个RLock实例。
不理解锁的,请看上一条随笔。
Condition():
- acquire(): 线程锁
- release(): 释放锁
- wait(timeout): 线程挂起,直到收到一个notify通知或者超时(可选的,浮点数,单位是秒s)才会被唤醒继续运行。wait()必须在已获得Lock前提下才能调用,否则会触发RuntimeError。
- notify(n=1): 通知其他线程,那些挂起的线程接到这个通知之后会开始运行,默认是通知一个正等待该condition的线程,最多则唤醒n个等待的线程。notify()必须在已获得Lock前提下才能调用,否则会触发RuntimeError。notify()不会主动释放Lock。
- notifyAll(): 如果wait状态线程比较多,notifyAll的作用就是通知所有线程
import threading
import time # 商品
product = None
# 条件变量
con = threading.Condition(threading.Lock()) # 生产者方法
def produce():
global product if con.acquire():
while True:
print('我执行了,produce')
if product is None:
product = 'anything'
print('produce...',product)
print('plock=',con)
# 通知消费者,商品已经生产
con.notify() # 等待通知
con.wait()
time.sleep(2) # 消费者方法
def consume():
global product if con.acquire():
while True:
print('我执行了,consume')
if product is not None:
print('consume...',product)
print('clock=',con)
product = None # 通知生产者,商品已经没了
con.notify() # 等待通知
con.wait()
time.sleep(2) t2 = threading.Thread(target=consume)
t2.start()
t1 = threading.Thread(target=produce)
t1.start()
1、生产者消费者模型
import threading
import time condition = threading.Condition()
products = 0 class Producer(threading.Thread):
def run(self):
global products
while True:
if condition.acquire():
if products < 10:
products += 1;
print "Producer(%s):deliver one, now products:%s" %(self.name, products)
condition.notify()#不释放锁定,因此需要下面一句
condition.release()
else:
print "Producer(%s):already 10, stop deliver, now products:%s" %(self.name, products)
condition.wait();#自动释放锁定
time.sleep(2) class Consumer(threading.Thread):
def run(self):
global products
while True:
if condition.acquire():
if products > 1:
products -= 1
print "Consumer(%s):consume one, now products:%s" %(self.name, products)
condition.notify()
condition.release()
else:
print "Consumer(%s):only 1, stop consume, products:%s" %(self.name, products)
condition.wait();
time.sleep(2) if __name__ == "__main__":
for p in range(0, 2):
p = Producer()
p.start() for c in range(0, 3):
c = Consumer()
c.start()
2、生产者消费者模型
import threading alist = None
condition = threading.Condition() def doSet():
if condition.acquire():
while alist is None:
condition.wait()
for i in range(len(alist))[::-1]:
alist[i] = 1
condition.release() def doPrint():
if condition.acquire():
while alist is None:
condition.wait()
for i in alist:
print i,
condition.release() def doCreate():
global alist
if condition.acquire():
if alist is None:
alist = [0 for i in range(10)]
condition.notifyAll()
condition.release() tset = threading.Thread(target=doSet,name='tset')
tprint = threading.Thread(target=doPrint,name='tprint')
tcreate = threading.Thread(target=doCreate,name='tcreate')
tset.start()
tprint.start()
tcreate.start()
3、生产者消费者模型
import threading def run(n):
con.acquire()
print('我执行了',threading.current_thread().name)
con.wait()
print("run the thread: %s" %n)
con.release() if __name__ == '__main__': con = threading.Condition()
for i in range(10):
t = threading.Thread(target=run, args=(i,))
t.start() while True:
inp = input('>>>') if inp == 'q':
break
con.acquire()
con.notify(int(inp))
con.release()
总结
1、release和wait都有释放锁的作用,不同在于wait后,该子线程就在那里挂起等待,要继续执行,就需要接收到notify或者notifyAll来唤醒线程,而release该线程还能继续执行。
2、notify和notifyAll的区别在于,notify只能唤醒一个wait,而notifyAll能唤起所有wait。
python Condition类(锁)的更多相关文章
- Java:多线程,使用同步锁(Lock)时利用Condition类实现线程间通信
如果程序不使用synchronized关键字来保证同步,而是直接使用Lock对象来保证同步,则系统中不存在隐式的同步监视器,也就不能用wait().notify().notifyAll()方法进行线程 ...
- python线程condition条件锁应用实例
import time import threading # 吃火锅鱼丸 guo = [] suo = threading.Condition() #条件锁 # 生产者负责生产 class Produ ...
- 并发编程---线程 ;python中各种锁
一,概念 在传统操作系统中,每个进程有一个地址空间,而且默认就有一个控制线程 线程顾名思义,就是一条流水线工作的过程,一条流水线必须属于一个车间,一个车间的工作过程是一个进程 --车间负责把资源整合到 ...
- python多进程没有锁队列范例
假设有一些任务要完成.为了完成这项任务,将使用几个过程.所以,将保持两个队列.一个包含任务,另一个包含已完成任务的日志. 然后实例化流程来完成任务.请注意,python队列类已经同步. 这意味着,我们 ...
- muduo网络库学习之MutexLock类、MutexLockGuard类、Condition类、CountDownLatch类封装中的知识点
一.MutexLock 类 class MutexLock : boost::noncopyable 二.MutexLockGuard类 class MutexLockGuard : bo ...
- 孤荷凌寒自学python第四十天python 的线程锁RLock
孤荷凌寒自学python第四十天python的线程锁RLock (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 因为研究同时在多线程中读写同一个文本文件引发冲突,所以使用Lock锁尝试同步, ...
- 孤荷凌寒自学python第三十九天python 的线程锁Lock
孤荷凌寒自学python第三十九天python的线程锁Lock (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 当多个线程同时操作一个文件等需要同时操作某一对象的情况发生时,很有可能发生冲突, ...
- java多线程,多线程加锁以及Condition类的使用
看了网上非常多的运行代码,很多都是重复的再说一件事,可能对于java老鸟来说,理解java的多线程是非常容易的事情,但是对于我这样的菜鸟来说,这个实在有点难,可能是我太菜了,网上重复的陈述对于我理解这 ...
- Python的条件锁与事件共享
1:事件机制共享队列: 利用消息机制在两个队列中,通过传递消息,实现可以控制的生产者消费者问题要求:readthread读时,writethread不能写:writethread写时,readthre ...
随机推荐
- vue2.0中router-link详解
vue2.0中router-link详解:https://blog.csdn.net/lhjuejiang/article/details/81082090 在vue2.0中,原来的v-link指令已 ...
- P3806 【模板】点分治1(题解)(点分治)
P3806 [模板]点分治1(题解)(点分治) 洛谷题目传送门 #include<iostream> #include<cstdlib> #include<cstdio& ...
- python 丰田经销商
import requests import json from dbutil.pgsql import PgsqlPipeline from datetime import date headers ...
- k8s<------docker
- 1481:Maximum sum (前缀和+dp)
[题目描述] 对一个序列A={a1, a2,..., an}给出函数: t1 t2 d(A) = max{ ∑ai + ∑aj | 1 <= s1 <= t1 < s2 <= ...
- C中char类型的用法
代码 /* char类型的用法 */ #include <stdio.h> main(int argc, char *argv[]) { /* 声明字符变量c1 */ char c1 = ...
- 【记录】mysql 查看某数据库各个表容量大小SQL
有时候我们可能需要了解数据库中各个表的容量及大小,好了解数据库情况. 现只需要一条SQL就可以直观的展示出来. SELECT table_schema AS '数据库', table_name AS ...
- Oracle:同步两张表的相同字段
有一个需求需要同步两张表的相同字段,比如表A和表B,这两张表是不同的用户下的表,表结构是一样的. 一开始我简单写了一个sql语句,如下: update ord_log1 A set (A.pid, A ...
- 八核浮点型DSP的双千兆网接口设计方案
千兆网络接口具有数据传输速率快.连接方便.可以即插即用的优点,使得其应用较为广泛.随着电子技术和处理器的发展,很多应用场合的数据通信速率超过千兆网口的实际传输速率.例如,在A/D采样中,需要直接存储A ...
- java 字符串常量池