簡體   English   中英

使用鎖C鎖定數組的元素

[英]Locking elements of an array using locks C++

我所擁有的是一個數組,我想在一個元素上放置一個鎖,以便另一個元素無法更改它。

一種更好地描述這一點的方法是向您展示:

Array A = new Array;

Thread1() {

  while(array hasn't been completely changed)  { 
     grab lock for random element within the array
     alter the elements to this array
     free the lock for the element
  }
}

Thread2() {

  while(array hasn't been completely changed)  { 
     grab lock for random element within the array
     alter the elements to this array
     free the lock for the element
  }
}

目標是使兩個線程都對元素執行操作但將其鎖定,以便其他線程無法訪問它。

Yoy可能希望使用互斥鎖作為以下示例代碼:

#include <mutex>
#include <thread>

using namespace std;


mutex mtx[12];
int   A  [12];

auto modArray = [&mtx, &A](int position){
    while(!mutex[i].try_lock());
    modifiyArrayAtIndex(A, i);
    mtx[i].unlock();
};

thread t1(modArray, 5);
thread t2(modArray, 5);
thread t3(modArray, 6);
thread t4(modArray, 6);
t1.join();
t2.join();
t3.join();
t4.join();

只需將數組與大小相等的互斥鎖數組匹配,即可鎖定與您可能要修改的索引對應的互斥鎖。 t1和t2線程正在處理索引5數據,而t3和t4線程正在處理索引6數據。

互斥鎖僅將訪問權限同步到線程之間所需的資源者,

while(!mtx.try_lock())

主動等待部分不是表現最佳的選擇,但可以勝任。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM