如何在运行之前启动两个线程并锁定它们,并仅在解锁时执行?

时间:2016-03-02 00:25:09

标签: python multithreading python-2.7 locking

我有这个示例代码来解释我的问题:

import threading
import time

class thread1(threading.Thread):

    def __init__(self, lock):
        threading.Thread.__init__(self)
        self.daemon = True
        self.start()        
        self.lock = lock

    def run(self):
        while True:
            self.lock.acquire(True)
            print ('write done by t1')
            self.lock.release()

class thread2(threading.Thread):

    def __init__(self, lock):
        threading.Thread.__init__(self)
        self.daemon = True
        self.start()        
        self.lock = lock

    def run(self):
        while True:
            self.lock.acquire(True)
            print ('write done by t2')
            self.lock.release()

if __name__ == '__main__':
    lock = threading.Lock()
    t1 = thread1(lock)
    t2 = thread2(lock)

    lock.acquire(True)

    counter = 0

    while True:
        print("main...")
        counter = counter + 1
        if(counter==5 or counter==10):
            lock.release() # Here I want to unlock both threads to run just one time and then wait until I release again
        time.sleep(1)

    t1.join()
    t2.join()

我遇到的一些问题如下:

我希望在程序开头有两个线程(thread1和thread2),但它们应该等到main() counter达到5或10。

main() counter达到5或10时,它应该发出信号/触发/解锁线程,threads只应运行一次,然后等到新{{1} }}

我希望代码具有以下输出(每行运行1秒):

unlock

相反,我有不同的行为,例如以:

开头
main...
main...
main...
main...
main...
write done by t1
write done by t2
main...
main...
main...
main...
main...
write done by t1
write done by t2

(等)

5秒后

write done by t1
write done by t1
write done by t1
write done by t1

很多次......

有人可以帮我解释错误吗?我该如何改进?

1 个答案:

答案 0 :(得分:1)

  1. 在thread1和thread2的__init __()中,在分配self.lock之前调用start()。
  2. t1和t2是在主线程获得锁定之前创建的。这使得这两个线程在主线程锁定它们之前开始打印。这就是你的代码打印前几行"由x"。
  3. 完成的原因
  4. 在计数器达到5之后,主线程释放锁,但它永远不会再锁定它。这使得t1和t2继续运行。
  5. 除非你杀了它,否则它永远不会退出......
  6. 我建议您使用 Condition Object 而不是Lock。

    以下是基于您的代码的示例。

    _.isEqual