如何使用等待和通知在线程之间进行通信? [英] How to communicate between threads with wait and notify?

查看:112
本文介绍了如何使用等待和通知在线程之间进行通信?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个线程在同一函数中运行.我想稍后在代码中编辑数据结构,但我想确保两个线程都已读取数据,并且这些线程不会读取dict_list和ans_list中的任何将来更改.我当时正在考虑在mutex.acquire()之前使用诸如wait()和notify()之类的命令,但是由于两个线程都使用相同的功能,因此第二个线程将不得不等待永远不会到来的通知.

I have 2 threads running in the same function. I want to edit the data structures later in the code, but I want to make sure that both the threads have read the data and any future changes in the dict_list and ans_list will not be read by these threads. I was thinking of making use of commands such as wait() and notify() just before mutex.acquire() but since both the threads are using the same function, the second thread will have to wait for a notify that will never come.

我该如何解决这个问题?

How can I approach this problem?

 def foo():

        //Reading the dict_list and ans_list here



        mutex.acquire()
        ans_list[room_no-1] = ""
        dict_list[room_no-1].clear()
        mutex.release()

推荐答案

我建议使用屏障来同步线程,以便在允许任何一个线程写入之前,它们两个都完成读取.所有线程必须先达到障碍,然后它们中的任何一个才能继续.

I would suggest using a barrier to synchronize the threads so that both of them finish reading before any of them is allowed to write. All the threads must reach the barrier before any of them can continue.

这可以通过条件和计数器来实现.代码如下:

This can be implemented via a Condition and a counter. The code looks like this:

lock = threading.Condition()
v = 0
n = 2

def barrier():
    global v # I forgot to add this line
    with lock:
        v += 1 # This was =+
        if v == n:
            lock.notifyAll()
            v = 0
        else:
            lock.wait()

用法如下:

read
barrier()
write

此实现适用于固定数量的线程.也有可能设计一种适用于动态数字的设计,但事实并非如此.

This implementation is for a fixed number of threads. It is also possible to have a design that works for a dynamic number but this is not it.

这篇关于如何使用等待和通知在线程之间进行通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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