簡體   English   中英

一個線程正在運行時阻止其他線程

[英]Blocking other Threads while one Thread is running

假設我有兩種類型的線程,

  1. 每x分鍾運行一次的單線程。 我們稱之為線程

  2. 多線程一直運行。 B線程何時A線程do_something()我希望所有B線程都等到A完成后再恢復它們。 我不知道該用什么。

我嘗試使用threading.Conditionwait() / notifyAll()但是它沒有按我的要求工作。 一旦我放入Condition,它將像同步線程之類的東西按1的順序進行處理。 我希望他們自由奔跑。

這是示例代碼,我嘗試將它們放置為wait() ,然后通知它們,但它像join()一樣按1的join() 不知道我們該怎么辦。

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()

問題 :一個線程正在運行時阻止其他線程

此示例不使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM