假设我有一个在多个线程/进程之间共享的(固定大小的)数组。
有没有一种(通用的,轻量级的)锁/互斥锁机制,这样如果我只想从数组中的某个位置读/写,就不必锁定对整个数组的访问?
一种蛮力方法是简单地为数组中的每个元素设置一个互斥锁。然而,这似乎有点超重,我正在寻找替代解决方案。
下面是一个简短的例子,来说明我的意思:
//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);
}发布于 2012-07-24 19:54:29
您可以简单地在您提到的两种方法之间进行权衡。具有较少数量的锁,每个锁保护阵列的一部分,即K个锁,每个锁保护N/K个项。
然后,根据应用程序中的数据访问模式,您可以使用条带化(即锁0保护索引0,K,2K,...锁定%1索引% 1,K+1,2K+1,...等)或者是一种连续的策略。
https://stackoverflow.com/questions/11630011
复制相似问题