用于同步的索引相关锁/互斥机制

时间:2012-07-24 11:35:50

标签: multithreading parallel-processing locking

假设我有一个在多个线程/进程之间共享的数组(固定大小)。

对于锁/互斥锁是否存在(通用的,最佳轻量级的)机制,因此如果我只想从数组中的某个位置读/写,我不必锁定对整个数组的访问权限。

蛮力方法是为数组中的每个元素简单地使用一个互斥锁。然而,这似乎有点超重,我正在寻找替代解决方案。

一个简短的例子,显示我的意思:

//Setup
int a[50];

void threada()
{
   lock(a,4); //supposed to lock index 4 of array a from access by other threads
   write(a,4); //writes something to index 4
   unlock(a,4); 
}

void threadb()
{
   //now all of this shouldn't block, since i'm accessing index 5, not 4
   lock(a,5); //supposed to lock index 5 of array a from access by other threads
   write(a,5); //writes something to index 5
   unlock(a,5);
}

void threadc()
{
   //all of this, however, should block if threada is already accessing it
   lock(a,4); //supposed to lock index 4 of array a from access by other threads
   write(a,4); //writes something to index 4
   unlock(a,4);
}

1 个答案:

答案 0 :(得分:2)

您可以简单地在您提到的两种方法之间进行权衡。拥有较少数量的锁,每个锁保护阵列的一部分,即K锁,每个锁保护N / K项。

然后,根据应用程序中的数据访问模式,您可以使用条带化(即锁定0保护索引0,K,2K,...锁定1索引1,K + 1,2K + 1,...等等)或连续策略。