简体   繁体   English

如何使用等待和通知在线程之间进行通信?

[英]How to communicate between threads with wait and notify?

I have 2 threads running in the same function.我有 2 个线程在同一个函数中运行。 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.我想在代码的后面编辑数据结构,但我想确保两个线程都读取了数据,并且这些线程不会读取 dict_list 和 ans_list 中的任何未来更改。 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.我正在考虑在 mutex.acquire() 之前使用诸如 wait() 和 notify() 之类的命令,但由于两个线程都使用相同的函数,因此第二个线程将不得不等待永远不会出现的通知。

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()

This is used like:这使用如下:

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.也可能有一个适用于动态数字的设计,但事实并非如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM