0

I have this

#threads 
import thread
import threading
import time

class ThreadTask(threading.Thread):
    def __init__(self,name,delay,callback):

        threading.Thread.__init__(self)

        self.name = name
        self.counter = 0
        self.delay = delay
        self.callback = callback
        self.lock = threading.Lock()

    def run(self):
        while True:
            self.counter += 1
            print 'running ', self.name , self.counter
            time.sleep(self.delay)

            if self.counter % 5 == 0:
                self.callback(self)


class Barrier(object):
    def __init__(self):
        self.locks = []

    def wait_task(self,task):
        print 'lock acquire'
        self.locks.append(task.lock)
        task.lock.acquire(True)
        task.lock.acquire(True)


    def notity_task(self,task):
        print 'release lock'
        for i in self.locks: 
            try:
                i.release()
            except Exception, e:
                print 'Error', e.message

            print 'Lock released'

       self.locks = []


try:
    barrier = Barrier()

    task1 = ThreadTask('Task_1',1,barrier.wait_task)
    task4 = ThreadTask('Task_4',1,barrier.wait_task)
    task3 = ThreadTask('Task_3',2,barrier.wait_task)
    task2 = ThreadTask('Task_2',3,barrier.notity_task)

    task2.start()
    task1.start()
    task3.start()
    task4.start()

except Exception as e:
    raise e

while 1:
    pass

These Thread run ok but if I put 2 task.lock.acquire(True) consecutive otherwise do not work, they stop each 10 when need to be each 5. Any one know what happening?

Thanks

4

1 回答 1

0

您在这里创建一个常规的、不可重入的锁:

    self.lock = threading.Lock()

然后尝试在这里获取两次

    task.lock.acquire(True)
    task.lock.acquire(True)

这是非法的,同一线程不能两次获取常规锁。

也许您的意思是使用threading.RLock()?

于 2014-03-27T08:34:58.993 回答