2009-05-20 49 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()