简体   繁体   English

信号量和共享内存

[英]Semaphores and shared memory

I have a question regarding multiprocess programming in C, I have several reader processes that will be reading from a file into a shared buffer and several writer processes reading from the buffer and into another file, what type of semaphores will we need to use for this. 关于C语言中的多进程编程,我有一个问题,我有几个读取器进程将从一个文件读取到一个共享缓冲区中,并且有几个写入器进程从该缓冲区读取到另一个文件中,为此我们需要使用哪种信号量? 。 and how can we use shared memory with the semaphores. 以及如何在信号量中使用共享内存。

If you're on linux, one easy option is to use pshared mutexes and condition variables. 如果您使用的是Linux,一种简单的选择是使用pshared互斥锁和条件变量。 A recet version of glibc will be necessary. 必须有glibc的Recet版本。 Essentially inside your shared memory segment you will have something like: 本质上,您在共享内存段中将具有以下内容:

struct shmem_head {
    pthread_mutex_t mutex;
};

To initialize: 初始化:

void init_shmem_head(struct shmem_head *head)
{
    pthread_mutexattr_t attr;
    pthread_mutexattr_init(&attr);
    pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED );

    pthread_mutex_init(&head->mutex, &attr);
    pthread_mutexattr_destroy(&head->mutex);
}

You now have a mutex, shared by all processes with the shared memory segment open. 现在,您将拥有一个互斥锁,在共享内存段打开的情况下,所有进程都可以共享它。 You can simply use pthread_mutex_lock to lock and pthread_mutex_unlock to unlock as normal. 您可以pthread_mutex_lock简单地使用pthread_mutex_lock锁定和pthread_mutex_unlock解锁。 There's also a similar pthread_condattr_setpshared if you want condition variables as well. 如果还需要条件变量,则还有一个类似的pthread_condattr_setpshared

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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