我只是在玩python中的线程,对python也是相当陌生的。我有一个producer类,我为其创建线程。这些线程都访问一个作为公共资源的单个对象。下面是代码
class Producer (threading.Thread):
def __init__(self, threadId, source):
threading.Thread.__init__(self)
self.source = source
self.threadId = threadId
def produce(self):
while 1:
data = self.source.getData()
if data == False:
print "===== Data finished for "+self.threadId+" ====="
break
else:
print data
def run(self):
self.produce()
#class
class A:
def __init__(self):
self.dataLimit = 5
self.dataStart = 1
def getData(self):
lock = Lock()
lock.acquire()
if self.dataStart > self.dataLimit:
return False
lock.release()
data = "data from A :: "+str(self.dataStart)+" Accessor thread :: "+thread.threadId
time.sleep(0.5)
lock.acquire()
self.dataStart += 1
lock.release()
return data
#def
#class
source = A()
for i in range(2):
thread = Producer( "t_producer"+str(i), source )
thread.start()
print "Main thread exiting..."
所以A级将dataStart从1计数到5。现在由于它是一个公共资源,getData方法也实现了锁,所以producer类的线程会交换访问getData方法,预期输出如下:
^{pr2}$但我得到的是:
data from A :: 1 Accessor thread :: t_producer0
data from A :: 1 Accessor thread :: t_producer1
data from A :: 3 Accessor thread :: t_producer1
data from A :: 3 Accessor thread :: t_producer1
data from A :: 5 Accessor thread :: t_producer1
===== Data finished for t_producer0 =====
data from A :: 5 Accessor thread :: t_producer1
===== Data finished for t_producer1 =====
如您所见,数据计数重复,随机计数丢失。如何处理这个问题?在
您在释放调用之前返回False。尝试使用
^{pr2}$with
语句,如下所示:这将确保获取并随后释放它。在
相关问题 更多 >
编程相关推荐