我最近一直在研究Python,当我探索一些关于线程的知识时遇到了一些问题.Thread。示例代码如下:
#!/usr/bin/env python3.0
# -*- coding: utf-8 -*-
#!/usr/bin/env python3.0
# -*- coding: utf-8 -*-
from threading import Condition, Thread
import time
class ProductAndConsumer(object):
""" test the threading.Condition function in python. the class will simulates a simple
Product and Consumer process mode
Attribute:
__con : a instance of threading.Condtion
—products: the list contains all products which is not consumed
"""
__con = Condition()
_products = []
def product(self, name):
""" the Producter that will product a product.
Args:
@name the name of the producted product
there are no return value
"""
if self.__con.acquire():
self._products.append('product-'+name)
print "product a product, the product's name is:" + name
self.__con.notify()
def consume(self):
""" get a product from product container(products) and consume it( remove it from products)
"""
if self.__con.acquire():
flag = True
while flag:
if len(self._products) <= 0:
print 'there are no products, wait......'
else:
print "consume a product,product'name is:"+self._product.pop() # consume a product
self.__con.wait()
pc = ProductAndConsumer()
Thread(target=pc.consume).start()
time.sleep(5)
Thread(target=pc.product, args=('xiaoxin',)).start()
打印结果如下:
there are no products, wait......
product a product, the product's name is:xiaoxin
为什么没有打印下面的字符串?
"consume a product,product'name is:product-xiaoxin
答案 0 :(得分:0)
首先,将消息线程函数中的错误self.__product.pop()
修复为self.__products.pop()
。
您需要在生产者线程中通知后释放条件。在通知后添加行self.__con.release()
。