Krab
Krab

Reputation: 6756

Synchronization of acces to shared memory

i have shared memory, x writers, y readers, one parent process. Writers have exclusive access, so one writer can write and other readers and writers must wait. Multiple readers can read parallel. Priority is on writers, so for example if 3 readers are reading and one writer want write to that shared memory, then when those 3 readers finish their job, no more readers can read and writer can write. I dont know how to implement it through semaphores, because readers can read parallel, so next code will not work, because then all readers will be waiting in that semaphore.

//reader
if(isWriterActive())
{
   sem_wait(semReaderStop);
} 

//writer
sem_wait(semReaderStop());
.
.
sem_post(semReaderStop());

I think something like this is not good, because it is not blocking.

//readers doJob
if(isWriterActive())
{
    return E_WRITER_ACTIVE;
}

while(doJob()==E_WRITER_ACTIVE);

Upvotes: 0

Views: 2490

Answers (2)

Gerardo Lima
Gerardo Lima

Reputation: 6703

Your problem is a variation of the classic Producer/Consumer problem (with no given read/write operations synchronization constraint). The following pseudo-code allows must solve your problem:

// globals
semaphore writers = 1; // "binary semaphore"
semaphore readers = 1; // "counting semaphore"

void writer() {
    sem_wait(writers); // wait until there's no writers
    sem_wait(readers); // wait until there's no readers

    // safe write context: no-one else can read nor write

    sem_post(readers); // signal other readers can run
    sem_post(writers); // signal other writers can run
}

void reader() {
    sem_wait(writers); // wait until there's no writers
    sem_post(readers); // there's one more reader active

    // safe read context: others can read, but no-one else can write

    sem_wait(readers); // this reader is completed
    sem_post(writers); // signal other writers can run
}

For more information on Synchronization see this lecture, but I'd recommend reading the more about Dijkstra Semaphores online or using a good book like Tanenbaum's Modern Operating Systems.

Upvotes: 0

Steve Townsend
Steve Townsend

Reputation: 54128

You need a Pthreads reader/writer lock - there is some background here on writer starvation on Linux NPTL.

Upvotes: 1

Related Questions