繁体   English   中英

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

[英]locking problems in a threading example in python

我只是在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 =====

如您所见,数据计数重复,缺少随机计数。 这里怎么处理这个问题?

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

这将确保获得然后释放它。

def getData(self):
        lock = threading.Lock()
        with lock:
            if self.dataStart > self.dataLimit:
                return False

            data = "data from A :: " + str(self.dataStart) + " Accessor thread :: " + thread.threadId
            self.dataStart += 1
        return data

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM