问题
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()
回答1:
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.
来源:https://stackoverflow.com/questions/60162894/how-to-communicate-between-threads-with-wait-and-notify