Let’s say I have an array (of fixed size) that is shared between multiple threads/processes.
Is there a (generalized, optimally lightweight) mechanism for a lock/mutex so that I don’t have to lock access to the entire array if I just want to read/write from a certain position in the array?
A brute force approach would be to simply have one mutex for each element in the array. However, this seems a bit overweight and I’m looking for alternative solutions.
A short example, to show what I mean:
//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);
}
You could simply have a trade-off between the two methods you mentioned. Have a smaller number of locks each protecting a section of the array i.e. K locks, each protecting N/K items.
Then, depending on the data access patterns in your application you can use a striped (i.e. lock 0 is protecting index 0, K, 2K,… lock 1 index 1, K+1, 2K+1,… etc.) or a contiguous strategy.