gpt4 book ai didi

python - python 线程示例中的锁定问题

转载 作者:行者123 更新时间:2023-11-30 23:39:24 26 4
gpt4 key购买 nike

我只是在 python 中玩弄线程,而且对 python 也很陌生。我有一个生产者类,我在其中创建线程。这些线程都访问作为公共(public)资源的单个对象。下面是代码

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。现在由于它是公共(public)资源,并且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 =====

正如您所看到的,数据计数是重复的,随机计数丢失。这里如何处理这个问题?

最佳答案

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)

您在发布调用之前返回 False。尝试使用 with 语句,如下所示:

with lock:
# Do stuff

这将确保获取并随后释放它。

关于python - python 线程示例中的锁定问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13590663/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com