在python中同步多个线程 [英] Synchronising multiple threads in python

查看:65
本文介绍了在python中同步多个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我需要 x 个线程等待,直到它们都达到同步点.我的解决方案使用下面的 synchronise 方法,每个线程函数在需要同步时都会调用该方法.

I have a problem where I need x threads to wait until they have all reached a synchronization point. My solution uses the synchronise method below which is called by each threaded function when they need to synchronise.

有没有更好的方法来做到这一点?

Is there a better way to do this?

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

推荐答案

同步线程的方法有很多种.很多.

There are many ways to synchronize threads. Many.

除了同步之外,您还可以执行以下操作.

In addition to synchronize, you can do things like the following.

  1. 围绕同步点将您的任务分为两个步骤.启动线程执行预同步步骤.然后使用join"等待所有线程完成第 1 步.开始执行同步后步骤的新线程.我更喜欢这个,而不是同步.

  1. Break your tasks into two steps around the synchronization point. Start threads doing the pre-sync step. Then use "join" to wait until all threads finish step 1. Start new threads doing the post-sync step. I prefer this, over synchronize.

创建队列;获取同步锁.启动所有线程.每个线程在队列中放置一个条目并等待同步锁.主"线程位于从队列中取出项目的循环中.当所有线程都将一个项目放入队列时,主"线程释放同步锁.所有其他线程现在可以再次自由运行.

Create a queue; acquire a synchronization lock. Start all threads. Each thread puts an entry in the queue and waits on the synchronization lock. The "main" thread sits in a loop dequeueing items from the queue. When all threads have put an item in the queue, the "main" thread releases the synchronization lock. All other threads are now free to run again.

有许多进程间通信 (IPC) 技术——所有这些技术都可用于线程同步.

There are a number of interprocess communication (IPC) techniques -- all of which can be used for thread synchronization.

这篇关于在python中同步多个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆