一个线程正在运行时阻止其他线程

时间:2019-07-11 05:24:36

标签: python python-3.x multithreading

假设我有两种类型的线程,

  1. 每x分钟运行一次的单线程。我们称它为线程

  2. 多线程始终运行。 B线程何时A线程do_something()我希望所有B线程都等到A完成后再恢复它们。我不知道该用什么。

我尝试使用threading.Conditionwait() / notifyAll(),但是它并没有按照我的要求工作。一旦我放入Condition,它将像同步线程之类的东西按1的顺序进行处理。我希望他们自由奔跑。

这是示例代码,我尝试将它们放置在wait()上,然后通知它们,但是它像join()一样按1的顺序进行处理。不知道我们该怎么办。

class ...
check = True
def xxx(self,g,con):
  for i in range(3):
    with con:
      if self.check:
        con.wait()
      self.check = False
      time.sleep(3)
      print(g)

con = threading.Condition()
threading.Thread(target=xxx,args=('a',con,)).start()
threading.Thread(target=xxx,args=('b',con,)).start()
threading.Thread(target=xxx,args=('c',con,)).start()
time.sleep(2)
con.notifyAll()

1 个答案:

答案 0 :(得分:0)

  

问题:在一个线程正在运行时阻止其他线程

此示例使用threading.Condition()而不是使用threading.Barrier(...)


docs.python.org中使用的模块:


import time, threading
from threading import BrokenBarrierError

def worker_A(g, terminate, barrier):
    # Counter to simulate conditional workload
    do_something = 3

    while not terminate.is_set():
        if do_something == 0:
            # Reset the barrier and wait until n_waiting == 2
            barrier.reset()
            while not terminate.is_set() and barrier.n_waiting < 2:
                time.sleep(0.5)

            # Now the other Threads waiting at the barrier
            # Simulate worklaod ...
            print('worker_A barrier.broken={} n_waiting={}'
                .format(barrier.broken, barrier.n_waiting))
            time.sleep(3)

            # Call the third barrier.wait to release the barrier
            try:
                barrier.wait()
            except BrokenBarrierError:
                pass

            # Reset counter to restart simulate conditional workload
            do_something = 3
        else:
            # Count down and give the other threads a timeslice
            do_something -= 1
            time.sleep(0.5)

def worker_B(g, terminate, barrier):
    while not terminate.is_set():
        # Simulate workload ...
        print('worker_B({})'.format(g))
        time.sleep(1)

        # Block at barrier.wait() if the barrier is NOT in the broken state
        try:
            barrier.wait()
        except BrokenBarrierError:
            pass

if __name__ == "__main__":
    # Event to terminate all Threads save
    terminate = threading.Event()

    # Barrier to block worker_B Threads
    # We use 3 Threads, therefore init with parties=3
    barrier = threading.Barrier(3)
    barrier.abort()

    # Create and start the Threads
    threads = []
    for t in [(worker_A, 'a'), (worker_B, 'b'), (worker_B, 'c'), ]:
        threads.append(threading.Thread(target=t[0], args=(t[1], terminate, barrier,)))
        threads[-1].start()
        time.sleep(0.2)

    # Simulating MAIN Thread
    time.sleep(20)

    # Set the `terminate` Event to True, 
    # and abort the barrier to force all Threads to terminate
    print('Terminate...')
    terminate.set()
    barrier.abort()

    # Wait until all Threads terminated
    for t in threads:
        t.join()

    print('EXIT MAIN')

使用Python测试:3.5

相关问题