python threading之Condition的例子

Python提供的Condition对象提供了对复杂线程同步问题的支持。Condition被称为条件变量,除了提供与Lock类似的acquire和release方法外,还提供了wait和notify方法。线程首先acquire一个条件变量,然后判断一些条件。如果条件不满足则wait;如果条件满足,进行一些处理改变条件后,通过notify方法通知其他线程,其他处于wait状态的线程接到通知后会重新判断条件。不断的重复这一过程,从而解决复杂的同步问题。

除了上面画的acquire方法、 release方法、notify方法、wait方法外还有notifyAll方法,不过notifyAll方法不常用。

51cto博客上我看到一篇博文中,形象的以二人对话 (生产者-消费者模)来解释上面的具体理论。

thread-talk

其中空格哥对应原理图中的A函数 ,西米对应的B 函数,每句话是doing操作,空格哥未“doing” 前,西米需要一直等待。最后,你来我往,直到最后都release掉,对话结束。由于代码太长,我给个精简版的,模拟上面的对话:

#coding:utf-8
#---- Condition
#---- 捉迷藏的游戏
import threading, time
class Hider(threading.Thread):
    def __init__(self, cond, name):
        super(Hider, self).__init__()
        self.cond = cond
        self.name = name
    def run(self):
        time.sleep(1) #确保先运行Seeker中的方法
        self.cond.acquire() #b
        print self.name + ': 我已经把眼睛蒙上了'
        self.cond.notify()
        self.cond.wait() #c
                         #f
        print self.name + ': 我找到你了 ~_~'
        self.cond.notify()
        self.cond.release()
                            #g
        print self.name + ': 我赢了'   #h
class Seeker(threading.Thread):
    def __init__(self, cond, name):
        super(Seeker, self).__init__()
        self.cond = cond
        self.name = name
    def run(self):
        self.cond.acquire()
        self.cond.wait()    #a    #释放对琐的占用,同时线程挂起在这里,直到被notify并重新占有琐。
                            #d
        print self.name + ': 我已经藏好了,你快来找我吧'
        self.cond.notify()
        self.cond.wait()    #e
                            #h
        self.cond.release()
        print self.name + ': 被你找到了,哎~~~'
cond = threading.Condition()
seeker = Seeker(cond, 'seeker')
hider = Hider(cond, 'hider')
seeker.start()
hider.start()
执行结果如下:

[root@361way condition]# python con3.py
hider: 我已经把眼睛蒙上了
seeker: 我已经藏好了,你快来找我吧
hider: 我找到你了 ~_~
seeker: 被你找到了,哎~~~
hider: 我赢了
便于对比,这里再给一个无限循环的例子。经典的生产者与消费者问题:假设有一群生产者(Producer)和一群消费者(Consumer)通过一个市场来交互产品。生产者的”策略“是如果市场上剩余的产品少于1000个,那么就生产100个产品放到市场上;而消费者的”策略“是如果市场上剩余产品的数量多余100个,那么就消费3个产品。用Condition解决生产者与消费者问题的代码如下:

import threading
import time
class Producer(threading.Thread):
    def run(self):
        global count
        while True:
            if con.acquire():
                if count > 1000:
                    con.wait()
                else:
                    count = count+100
                    msg = self.name+' produce 100, count=' + str(count)
                    print msg
                    con.notify()
                con.release()
                time.sleep(1)
class Consumer(threading.Thread):
    def run(self):
        global count
        while True:
            if con.acquire():
                if count < 100:
                    con.wait()
                else:
                    count = count-3
                    msg = self.name+' consume 3, count='+str(count)
                    print msg
                    con.notify()
                con.release()
                time.sleep(1)
count = 500
con = threading.Condition()
def test():
    for i in range(2):
        p = Producer()
        p.start()
    for i in range(5):
        c = Consumer()
        c.start()
if __name__ == '__main__':
    test()

时间: 2024-07-31 22:44:28

python threading之Condition的例子的相关文章

python threading模块线程锁的例子

python threading模块有两类锁:互斥锁(threading.Lock )和可重用锁(threading.RLock).两者的用法基本相同,具体如下: lock = threading.Lock() lock.acquire() dosomething-- lock.release() RLock的用法是将threading.Lock()修改为threading.RLock().便于理解,先来段代码: [root@361way lock]# cat lock1.py #!/usr/b

python中多线程的一个例子总是报错大家帮忙看看

问题描述 python中多线程的一个例子总是报错大家帮忙看看 解决方案 http://bbs.csdn.net/topics/390614709 解决方案二: ...找到原因了是t2里的args函数名没写对.............,还是谢谢各位了

python threading模块操作多线程介绍_python

python是支持多线程的,并且是native的线程.主要是通过thread和threading这两个模块来实现的.thread是比较底层的模块,threading是对thread做了一些包装的,可以更加方便的被使用.这里需要提一下的是python对线程的支持还不够完善,不能利用多CPU,但是下个版本的python中已经考虑改进这点,让我们拭目以待吧.     threading模块里面主要是对一些线程的操作对象化了,创建了叫Thread的class.一般来说,使用线程有两种模式,一种是创建线程

python threading编程中的LOCK和RLOCK(可重入锁)

找到一本PYTHON并发编辑的书, 弄弄.. #!/usr/bin/env python # -*- coding: utf-8 -*- import threading import time shared_resource_with_lock = 0 shared_resource_with_no_lock = 0 COUNT = 100000 shared_resource_lock = threading.Lock() class Box(object): lock = threadin

use python threading multi-thread test PostgreSQL &amp; mongodb insert tps

前面两篇测试了一下python单线程压mongo和PostgreSQL的性能. 相比PostgreSQL的pgbench, python用到的这两个驱动未使用异步接口, 对性能影响极大. http://blog.163.com/digoal@126/blog/static/1638770402015142858224/ http://blog.163.com/digoal@126/blog/static/16387704020151210840303/ 本文使用threading这个模块, 测试

Python threading多线程编程实例_python

Python 的多线程有两种实现方法: 函数,线程类 1.函数 调用 thread 模块中的 start_new_thread() 函数来创建线程,以线程函数的形式告诉线程该做什么 复制代码 代码如下: # -*- coding: utf-8 -*- import thread def f(name):   #定义线程函数   print "this is " + name   if __name__ == '__main__':   thread.start_new_thread(f

Python THREADING模块中的JOIN()方法深入理解_python

看了oschina上的两个代码,受益匪浅.其中对join()方法不理解,看python官网文档的介绍: join([timeout]):等待直到进程结束.这将阻塞正在调用的线程,直到被调用join()方法的线程结束.(好难翻译,应该是这个意思) 哈哈,这个易懂. join方法,如果一个线程或者一个函数在执行过程中要调用另外一个线程,并且待到其完成以后才能接着执行,那么在调用这个线程时可以使用被调用线程的join方法. 复制代码 代码如下: #-*- encoding: gb2312 -*- im

python使用mysql数据库的例子

一,安装mysql   如果是windows 用户,mysql 的安装非常简单,直接下载安装文件,双击安装文件一步一步进行操作即可. Linux 下的安装可能会更加简单,除了下载安装包进行安装外,一般的linux 仓库中都会有mysql ,我们只需要通过一个命令就可以下载安装: Ubuntu\deepin >>sudo apt-get install mysql-server >>Sudo apt-get install  mysql-client centOS/redhat &g

python编辑写vim脚本例子

Vim 插件是一个 .vim 的脚本文件,定义了函数.映射.语法规则和命令,可用于操作窗口.缓冲以及行.一般一个插件包含了命令定义和事件钩子.当使用 Python 编写 vim 插件时,函数外面是使用 VimL 编写,尽管 VimL 学起来很快,但 Python 更加灵活,例如可以用 urllib/httplib/simplejson 来访问某些 Web 服务,这也是为什么很多需要访问 Web 服务的插件都是使用 VimL + Python 编写的原因. 在开始编写插件之前,你需要确认 Vim