0

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);
Krab
  • 6,526
  • 6
  • 41
  • 78
  • This is the usual description of a reader/Writer lock. Have a look at the pthread_rwlock http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_rwlock_init.html – gastush Apr 30 '12 at 14:22
  • Never try to implement locking primitives yourself. Just use normal read/write locks (but make sure their behavior is such that writers don't starve). – ugoren Apr 30 '12 at 14:26
  • I need to use semaphores ( school). – Krab Apr 30 '12 at 14:30
  • Ok, i found solution http://en.wikipedia.org/wiki/Readers-writers_problem – Krab Apr 30 '12 at 14:42

2 Answers2

1

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

Community
  • 1
  • 1
Steve Townsend
  • 53,498
  • 9
  • 91
  • 140
0

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.

Gerardo Lima
  • 6,467
  • 3
  • 31
  • 47