2009-05-20 48 views
6

多線程我有我需要x線程等待,直到他們都達到了同步點的問題。我的解決方案使用下面的synchronise方法,當它們需要同步時,它由每個線程函數調用。同步在python

有沒有更好的方式來做到這一點?

thread_count = 0 
semaphore = threading.Semaphore() 
event = threading.Event() 

def synchronise(count): 
    """ All calls to this method will block until the last (count) call is made """ 
    with semaphore: 
     thread_count += 1 
     if thread_count == count: 
      event.set() 

    event.wait() 

def threaded_function(): 
    # Do something 

    # Block until 4 threads have reached this point 
    synchronise(4) 

    # Continue doing something else 

回答

1

有很多方法來同步線程。許多。

除了同步,你可以不喜歡的東西下面。

  1. 將您的任務分爲兩步,圍繞同步點。開始執行預同步步驟的線程。然後使用「加入」等到所有線程完成步驟1.開始執行後同步步驟的新線程。我更喜歡這個,通過同步。

  2. 創建隊列;獲取同步鎖。開始所有線程。每個線程在隊列中放入一個條目並等待同步鎖定。 「主」線程位於循環中,使隊列中的項目出隊。當所有線程都將一個項目放入隊列中時,「主」線程將釋放同步鎖定。所有其他線程現在可以再次運行。

有一些進程間通信(IPC)技術 - 所有這些技術都可用於線程同步。

+0

我探索你的第一個建議,但有一個需要有線程做兩個同步前和同步工作後不將努力分成2個任務。如果我沒有這個限制,你的解決方案將是理想的。 – 2009-05-20 13:05:59

2

你想要的功能,被稱爲 「barrier」。 (不幸的是,這個術語在談論線程時有兩個含義,所以如果你Google它,只是忽略文章,談論「memory barriers」 - 這是一個非常不同的東西)。

你的代碼看起來相當合理 - 它很簡單和安全。

我找不到的Python的任何障礙「標準」的實施,所以我建議你繼續使用你的代碼。

2

注意障礙已實現使用障礙as of Python 3.2

例子:

from threading import Barrier, Thread 

def get_votes(site): 
    ballots = conduct_election(site) 
    all_polls_closed.wait()  # do not count until all polls are closed 
    totals = summarize(ballots) 
    publish(site, totals) 

all_polls_closed = Barrier(len(sites)) 
for site in sites: 
    Thread(target=get_votes, args=(site,)).start()