c - 使用未声明的标识符 'PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP'

标签 c pthreads

我正在尝试在 macOS 10.14 上使用 gcc 在终端中使用 gcc 进行编译。

我已经包含了#define _GNU_SOURCE在我的 C 程序的顶部,以及 #include <pthread.h>

但是当我使用以下内容时:gcc input.c -o output -lpthread-pthread我收到以下错误。我也尝试过 -std=c99 :

input.c:50:33: error: use of undeclared identifier
'PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP'
pthread_mutex_t request_mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;

这是我的代码摘要:

输入.c:

#define _GNU_SOURCE
#include <stdlib.h>
…
#include <pthread.h>

pthread_mutex_t request_mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;

int main(int argc, char* argv[])
{
  ...
}

编辑

我能够通过删除 _NP 来使代码正常工作在 PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP 末尾。感谢大家的建议。

最佳答案

PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP 是一个非标准扩展,显然 MacOS 不支持它。

您应该在 main() 开头初始化互斥体:

#include <stdio.h>
#include <string.h>
#include <pthread.h>

pthread_mutex_t request_mutex;

int init_recursive_mutex(pthread_mutex_t *mutex)
{
    pthread_mutexattr_t attr;
    int r;

    r = pthread_mutexattr_init(&attr);
    if (r != 0)
        return r;

    r = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);

    if (r == 0)
        r = pthread_mutex_init(mutex, &attr);

    pthread_mutexattr_destroy(&attr);

    return r;
}

int main(int argc, char* argv[])
{
    int r;

    r = init_recursive_mutex(&request_mutex);
    if (r != 0)
    {
        fprintf(stderr, "Failed to initialise request_mutex: %s\n", strerror(r));
        return 1;
    }

    /* ... */
}

关于c - 使用未声明的标识符 'PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53075327/

相关文章:

从 C 中的数组更改变量中的字符串

python - ldexp 和 frexp 的含义?

c - 在其他线程执行 mutex_unlock() 之后,等待互斥体的线程是否会立即获得所有权?

c - 为什么我的线程在第二次运行打印一行后停止?

条件变量适用于 MacOS 但不适用于 Ubuntu

c - 线程传递参数

c - 管道、子进程和子进程的范围

C 跳过函数

c++ - boost::atomic 真的可以通过减少多线程系统调用(在互斥/信号量中)的开销来 boost 性能吗?

python - 带有回调到 python VM 的 pthread