我只是在玩 python 中的线程,对 python 也很陌生。我有一个创建线程的生产者类。这些线程都访问作为公共资源的单个对象。下面是代码
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 方法也实现了锁定,生产者类的线程将交替访问 getData 方法,预期输出如下:
data from A :: 1 Accessor thread :: t_producer0
data from A :: 2 Accessor thread :: t_producer1
data from A :: 3 Accessor thread :: t_producer1
data from A :: 4 Accessor thread :: t_producer0
data from A :: 5 Accessor thread :: t_producer0
===== Data finished for t_producer0 =====
===== Data finished for t_producer1 =====
但我得到了这个:
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 =====
如您所见,数据计数重复,随机计数丢失。这里如何处理这个问题?