简体   繁体   中英

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);

你需要一个P线程读取/写入器锁-有一些背景这里在Linux NPTL作家饥饿。

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM