Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 对共享内存的访问同步_C_Linux_Unix_Synchronization_Semaphore - Fatal编程技术网

C 对共享内存的访问同步

C 对共享内存的访问同步,c,linux,unix,synchronization,semaphore,C,Linux,Unix,Synchronization,Semaphore,我有共享内存,x个编写器,y个阅读器,一个父进程。作者拥有独占访问权限,因此一位作者可以写作,而其他读者和作者必须等待。多个读卡器可以并行读取。优先级取决于编写器,例如,如果3个读卡器正在阅读,而一个编写器希望写入共享内存,那么当这3个读卡器完成其工作时,就没有更多的读卡器可以阅读,而编写器可以写入。我不知道如何通过信号量实现它,因为读卡器可以并行读取,所以下一个代码将不起作用,因为所有读卡器都将在该信号量中等待 //reader if(isWriterActive()) { sem_wa

我有共享内存,x个编写器,y个阅读器,一个父进程。作者拥有独占访问权限,因此一位作者可以写作,而其他读者和作者必须等待。多个读卡器可以并行读取。优先级取决于编写器,例如,如果3个读卡器正在阅读,而一个编写器希望写入共享内存,那么当这3个读卡器完成其工作时,就没有更多的读卡器可以阅读,而编写器可以写入。我不知道如何通过信号量实现它,因为读卡器可以并行读取,所以下一个代码将不起作用,因为所有读卡器都将在该信号量中等待

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

//writer
sem_wait(semReaderStop());
.
.
sem_post(semReaderStop());
我认为这样的东西不好,因为它没有阻塞

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

while(doJob()==E_WRITER_ACTIVE);

您需要一个Pthreads读写器锁-Linux NPTL上存在一些写器饥饿的背景知识。

您的问题是经典的生产者/消费者问题的一个变体(没有给定的读写操作同步约束)。以下伪代码允许您必须解决您的问题:

// 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
}

有关同步的更多信息,请参见本文,但我建议您阅读更多有关联机的信息或使用类似Tanenbaum的好书。

这是对读写器锁的常见描述。看看pthread_rwlock,千万不要自己尝试实现锁定原语。只需使用普通的读/写锁(但确保它们的行为不会让编写者挨饿)。我需要使用信号量(学校)。好的,我找到了解决方案否,我只能使用信号量。你确定不允许使用
rw\u信号量