Hey guys i was thinking on how we can make a file read by n readers and only one writer in which each operation has a different offset and size. With this motive i would like to have:-
1) Maximum concurrency
2) Preventing readers from reading regions of file where writer is writing to any offset in that region
3) however multiple readers can read overlapping area of file whenever writer does not have any overlap with the readers
4) Lastly readers should also not starve the writer
How can we achieve this situation using n+1 semaphore. Is there any example solution which i can refer. Thanks
Here is my psuedo code:-
lock
lock lockarray[m+1]
lockentry = set Lock Entry[Item number]
writer code:
wait(mutex[item number]);
readcount[item number]--;
if read count[item number]==0
signal (wrt[item number]);
signal (mutex[item number])
}
lock
lock lockarray[m+1]
lockentry = set Lock Entry[Item number]
Reader code:
wait(mutex[item number]);
read count[item number]++;
if read count[item number]==1
wait (wrt[item number]);
wait(mutex[item number]);
signal mutex[item number];
If you want to do it on a file you can define a certain granularity and declare locks based on that granularity. For example for large files you can use a size of 4k (size of a page on a system) and say that each r/w lock has a granularity of 4k on the file and the number of locks is simply size of file / 4k. You can use any arbitrary size that you want and of course there’s a tradeoff between more fine grain locking (more memory to keep track of region locks) and achieving the best performance.
You can try something like
To lock on a granularity lock all you have to do is find which lock you need to grab and do the normal R/W lock behavior.