【问题标题】:Semaphores and shared memory信号量和共享内存
【发布时间】:2011-06-20 16:04:38
【问题描述】:

我有一个关于 C 中的多进程编程的问题,我有几个读取器进程将从一个文件读取到共享缓冲区和几个写入器进程从缓冲区读取到另一个文件,我们需要什么类型的信号量用于此。以及我们如何将共享内存与信号量一起使用。

【问题讨论】:

  • 什么操作系统?您是否在使用任何多处理特定库?
  • linux 这里是我包含在文件中的所有头文件,#include #include #include #include #include #include #include #include #include #include #include

标签: c multiprocessing semaphore shared-memory


【解决方案1】:

如果您使用的是 linux,一个简单的选择是使用 pshared mutexes 和条件变量。需要一个接收版本的 glibc。基本上在您的共享内存段内,您将拥有如下内容:

struct shmem_head {
    pthread_mutex_t mutex;
};

初始化:

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

您现在有一个互斥体,由所有进程共享,共享内存段打开。您可以简单地使用pthread_mutex_lock 锁定和pthread_mutex_unlock 正常解锁。如果您还需要条件变量,还有一个类似的pthread_condattr_setpshared

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-27
    • 2010-10-26
    • 1970-01-01
    • 1970-01-01
    • 2015-01-13
    • 2020-04-29
    相关资源
    最近更新 更多