假设我有一个在多个线程/进程之间共享的数组(固定大小)。
是否存在用于锁定/互斥锁的(通用的、最佳轻量级的)机制,这样如果我只想从数组中的某个位置读/写,我就不必锁定对整个数组的访问?
一种蛮力方法是简单地为数组中的每个元素设置一个互斥锁。但是,这似乎有点超重,我正在寻找替代解决方案。
一个简短的例子,说明我的意思:
//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);
}