c++ - 基于 pthread_mutex 的进程间通信不起作用

标签 c++ linux pthreads

我目前正在尝试使用 pthread_mutex 模型在 Linux 中同步两个进程。

这是我正在处理的代码:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

using namespace std;

int main (int argc, char **argv)
{
    printf ("starting process\n");

    if (_POSIX_THREAD_PROCESS_SHARED == -1) {
        printf ("shared mutex is not supported!\r\n");
    }

    pthread_mutexattr_t attr;
    pthread_mutex_t shm_mutex;


    if (pthread_mutexattr_init(&attr) != 0)
        printf ("init attr error!\r\n");
    if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL) != 0)
        printf ("set type error!\r\n");
    if (pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED) != 0)
        printf ("set shared error!\r\n");

    int value;
    if (pthread_mutexattr_getpshared(&attr, &value) != 0 || value != PTHREAD_PROCESS_SHARED) {
        printf ("mutex is not shared!\r\n");
    }

    if (pthread_mutex_init(&shm_mutex, &attr) != 0)
        printf ("mutex init error!\r\n");

    for (int i=0; i < 10; i++) {

        if (pthread_mutex_lock(&shm_mutex) != 0)
            printf ("lock error!\r\n");

        printf ("begin run %d\r\n", i);
        sleep(10);
        printf ("end run %d\r\n", i);

        if (pthread_mutex_unlock(&shm_mutex) != 0)
            printf ("unlock error!\r\n");

        sleep(1); // sleep 1 second
    }

    pthread_mutex_destroy(&shm_mutex);
    pthread_mutexattr_destroy(&attr);

    return 0;
}

当我运行两个单独的进程时,开始/结束逻辑不起作用。

代码有问题吗?

最佳答案

您应该自己在共享内存中分配 shm_mutex。请参阅 man shm_overview。该标志仅表示您可以使用互斥锁执行此操作。

参见 this reference获取更多详细信息。

关于c++ - 基于 pthread_mutex 的进程间通信不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41603337/

相关文章:

c++ - Linux 3.14 关闭过早退出程序的文件句柄时的策略

c++ - 在 lambda 函数中捕获 boost::asio::thread_pool

c++ - Arduino 仅在代码的一部分延迟

python - ALSA & Python - 捕获多个单声道音频输入

android - 使用 Android NDK 使用 clang++ 编译 C++ 代码时未定义对 `_Unwind_Resume' 的引用

php - grep 命令输出中的特定字符串

编写一个基本的多线程程序

c - pthread_create 中遇到的错误

c++ - POSIX - pthread_kill()?

c++ - 是否可以指定一个可选的返回类型并在未指定的情况下推断它?