Ric*_*man 6 python multithreading synchronize
我有一个问题,我需要x线程等到它们都达到同步点.我的解决方案使用synchronise下面的方法,当需要同步时,每个线程函数调用该方法.
有一个更好的方法吗?
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
Run Code Online (Sandbox Code Playgroud)
同步线程的方法有很多种。许多。
除了同步之外,您还可以执行以下操作。
围绕同步点将您的任务分成两个步骤。启动线程执行预同步步骤。然后使用“join”等待所有线程完成步骤 1。启动新线程执行同步后步骤。与同步相比,我更喜欢这个。
创建队列;获取同步锁。启动所有线程。每个线程都会在队列中放入一个条目并等待同步锁。“主”线程位于循环中,使项目从队列中出列。当所有线程都将一个项目放入队列时,“主”线程释放同步锁。所有其他线程现在都可以再次自由运行。
有许多进程间通信(IPC)技术——所有这些技术都可以用于线程同步。