0
我有一個C++程序,我創建多個線程並讓他們訪問共享數組。pthread_mutex更新不夠快,所以一個線程會「鎖定」鎖。
每次我想一個線程訪問數組,我叫
pthread_mutex_lock(&mutex);
訪問數組 ,然後調用
pthread_mutex_unlock(&mutex);
的所有線程不斷循環,直到他們已經訪問數組一定次數。因此,他們不只是訪問一次數組,而是訪問它幾次。
現在,當我執行我的計劃只是因爲它是,無論哪個線程首先獲取互斥體(通常是創建的第一個線程)執行,直到它完成,允許另一個線程訪問前陣。
如果我添加一個簡單的睡眠()後面
pthread_mutex_unlock(&mutex);
然後線程將交替訪問陣列(這是我想要的)。我寧願不必使用sleep()來實現這一點。
據我所知,我相信這是發生了什麼事:
Thread A locks the mutex and begins accessing the array
Thread B tries to lock the mutex but finds its locked, therefore it waits
Thread A finishes with the array and unlocks the mutex
Thread A loops and relocks the mutex before Thread B realizes that Thread A unlocked the matrix
因此線程A繼續訪問陣列,直到它訪問了N次,即可完成與線程B訪問陣列的n次
反正是有使線程等待(互斥鎖解鎖),更新速度更快,只要它的解鎖獲取鎖?
我寧願上面的輸出是沿着線的東西更多:
Thread A locks the mutex and begins accessing the array
Thread B tries to lock the mutex but finds its locked, therefore it waits
Thread A finishes with the array and unlocks the mutex
Thread B sees the mutex is unlocked and locks it
Thread A loops and tries to lock the mutex, but finds its locked, therefore it waits
... etc.