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

时间:2012-11-27 18:27:32

标签: python multithreading

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

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

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:-1)

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