I think posting the actual problem will help
I am trying to implement a reader/writer lock on shared memory accessed by multiple process..Suppose we have a shared memory segment shared between 3 processes.
Each of these processes keeps trying to write to the memory or read from it
randomly. We are to allow only one writer at a time to prevent an inconsistent
value from being written. Implement this using semaphore. Keep in mind that
multiple readers can be allowed at once. Also, make sure that no process is
starved in getting access to the shared memory i.e. there is no possibility of an
infinite waiting time.
its like this:
every process can access the shared memory and read/write at random..
only one writer should be writing at any given point of time..
where as any number of readers can read at the same time..
there should not be starvation too..
I know to use semaphores & shared memory.. I am asking if this is the right way to do it..
here is the pseudo-code for a process
(my coding style will be little weird, as I put P()= increase & V() = decrease.. anyway this is not a problem as long as we a make sure that end is always 0, you can suggest your method with conventional P(), V())
is this how it is done?Code:/******************************************************* * assume that following are semaphores and * are initialized in the parent process as follows * initialize_semaphore anyone_inside = 0 * initialize_semaphore writers_waiting = 0 * initialize_semaphore write_mode = 0 * Blue colored statements are executed in one semop ********************************************************/ int main() { /* all stupid stuff here */ /* process trying to access critical section */ if( want_to_read ) { if(sem_wait(writers_waiting)) // wait till writers_waiting = 0 { if( sem_wait(write_mode)) // wait till write_mode = 0 { P(anyone_inside); // increment => anyone_inside++; read(); V(anyone_inside); // decrement => anyone_inside--; } } } else // trying to write { P(writers_waiting); // increment => writers_waiting++ if(sem_wait(anyone_inside)) // wait till anyone_inside = 0 { P(anyone_inside);// increment => anyone_inside++; P(write_mode); // increment => write_mode = 1; V(writers_waiting); // decrement => writers_waiting--; write(); V(write_mode); // decrement => write_mode-- V(anyone_inside); // decrement => anyone_inside-- } } }
will this work?
or any betterway?
P.S: the trivial single semaphore solution like one process at a time access is not needed