[英]How to communicate between threads with wait and notify?
我有 2 個線程在同一個函數中運行。 我想在代碼的后面編輯數據結構,但我想確保兩個線程都讀取了數據,並且這些線程不會讀取 dict_list 和 ans_list 中的任何未來更改。 我正在考慮在 mutex.acquire() 之前使用諸如 wait() 和 notify() 之類的命令,但由於兩個線程都使用相同的函數,因此第二個線程將不得不等待永遠不會出現的通知。
我該如何解決這個問題?
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()
我建議使用屏障來同步線程,以便它們都在允許寫入之前完成讀取。 所有線程必須先到達屏障,然后才能繼續。
這可以通過條件和計數器來實現。 代碼如下所示:
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
此實現適用於固定數量的線程。 也可能有一個適用於動態數字的設計,但事實並非如此。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.