Python多线程之条件变量Condition的使用

1.wait()方法会将使用该方法的线程挂起,并释放占用的Lock(由于这个Lock是Condition隐含的Lock.因此可以对实例化的Condition对象进行acquire()操作).
2.notify()会唤醒某个挂起的线程进入竞争Lock资源状态.
简单范例:

<pre>
#-*-encoding:utf-8-*-
import sys,time
import threading
reload(sys)
sys.setdefaultencoding('utf-8')

cond = threading.Condition()
def p1():
    global cond
    while True:
        cond.acquire()
        print "1 Got Lock"
        cond.notify()
        print "1 notify 2"
        cond.wait()
        print '1 is waked up'
        time.sleep(3)
   
def p2():
    global cond
    while True:
        cond.acquire()
        print "2 Got Lock"
        cond.notify()
        print "2 notify 1"
        cond.wait()
        print '2 is waked up'
        time.sleep(3)
   
   
t1 = threading.Thread(target=p1)
t2 = threading.Thread(target=p2)
t1.start()
t2.start()
</pre>