#!/usr/bin/evn python
#-*-encoding:utf8-*-
#这个程序会死锁,因为notify()函数是随机唤醒的,唤醒的不一定是生产者。当其他生产者都在wait,而消费者唤醒的确是另外一个消费者那么久死锁了
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import threading,time
conn = threading.Condition()
count = 7
class productor(threading.Thread):
# def __init__(self):
# super(threading.Thread,self).__init__()
def run(self):
global count
while True:
if conn.acquire():
if count >= 1:
conn.wait()
else:
count +=1
print self.getName()+'生产了 1 个'+u'现在的产品个数是:'+str(count)
conn.notify()
conn.release()
time.sleep(1)
class consumer(threading.Thread):
# def __init__(self):
# super(threading.Thread,self).__init__()
def run(self):
global count
while True:
if conn.acquire():
if count <=0:
conn.wait()
else:
count = count - 1
print self.getName()+'消费了 1 个'+u'现在的产品个数是:'+str(count)
conn.notify()
conn.release()
time.sleep(1)
if __name__ == '__main__':
for x in xrange(2):
t=productor()
t.start()
for x in xrange(5):
t=consumer()
t.start()
#-*-encoding:utf8-*-
#这个程序会死锁,因为notify()函数是随机唤醒的,唤醒的不一定是生产者。当其他生产者都在wait,而消费者唤醒的确是另外一个消费者那么久死锁了
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import threading,time
conn = threading.Condition()
count = 7
class productor(threading.Thread):
# def __init__(self):
# super(threading.Thread,self).__init__()
def run(self):
global count
while True:
if conn.acquire():
if count >= 1:
conn.wait()
else:
count +=1
print self.getName()+'生产了 1 个'+u'现在的产品个数是:'+str(count)
conn.notify()
conn.release()
time.sleep(1)
class consumer(threading.Thread):
# def __init__(self):
# super(threading.Thread,self).__init__()
def run(self):
global count
while True:
if conn.acquire():
if count <=0:
conn.wait()
else:
count = count - 1
print self.getName()+'消费了 1 个'+u'现在的产品个数是:'+str(count)
conn.notify()
conn.release()
time.sleep(1)
if __name__ == '__main__':
for x in xrange(2):
t=productor()
t.start()
for x in xrange(5):
t=consumer()
t.start()