C语言 静态 pthread 互斥初始化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5138778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:55:14  来源:igfitidea点击:

Static pthreads mutex initialization

cpthreadsmutexstatic-initialization

提问by ManRow

Using pthreads, how would one, in C, initialize a static array of mutexes?

使用 pthreads,如何在 C 中初始化一个静态互斥体数组?

For a single static mutex, it seems I can use PTHREAD_MUTEX_INITIALIZER. But what about an static array of them? As, in for example,

对于单个静态互斥锁,我似乎可以使用 PTHREAD_MUTEX_INITIALIZER。但是它们的静态数组呢?例如,

#include <pthread.h>
#define NUM_THREADS 5

/*initialize static mutex array*/
static pthread_mutex_t mutexes[NUM_THREADS] = ...?

Or must they be allocated dynamically?

还是必须动态分配?

采纳答案by Jens Gustedt

If you have a C99 conforming compiler you can use P99to do your initialization:

如果您有符合 C99 的编译器,则可以使用P99进行初始化:

static pthread_mutex_t mutexes[NUM_THREADS] =
  { P99_DUPL(NUM_THREADS, PTHREAD_MUTEX_INITIALIZER) };

This just repeats the token sequence PTHREAD_MUTEX_INITIALIZER,the requested number of times.

这只是将令牌序列重复PTHREAD_MUTEX_INITIALIZER,请求的次数。

For this to work you only have to be sure that NUM_THREADSdoesn't expand to a variable but to a decimal integer constant that is visible to the preprocessor and that is not too large.

为此,您只需确保NUM_THREADS它不会扩展为变量,而是扩展为预处理器可见的十进制整数常量,并且不会太大。

回答by paxdiablo

No, you don't have to create them dynamically. You can use a static array, you just have to get them all set up before you use them. You can do:

不,您不必动态创建它们。您可以使用静态数组,只需在使用它们之前将它们全部设置好。你可以做:

#define NUM_THREADS 5
static pthread_mutex_t mutexes[NUM_THREADS] = {
    PTHREAD_MUTEX_INITIALIZER,
    PTHREAD_MUTEX_INITIALIZER,
    PTHREAD_MUTEX_INITIALIZER,
    PTHREAD_MUTEX_INITIALIZER,
    PTHREAD_MUTEX_INITIALIZER
};

which is prone to errors if you ever change NUM_THREADS, though that can be fixed with something like:

如果您更改NUM_THREADS,这很容易出错,尽管可以通过以下方式修复:

static pthread_mutex_t mutexes[] = {
    PTHREAD_MUTEX_INITIALIZER,
    PTHREAD_MUTEX_INITIALIZER,
    PTHREAD_MUTEX_INITIALIZER,
    PTHREAD_MUTEX_INITIALIZER,
    PTHREAD_MUTEX_INITIALIZER
};
#define NUM_THREADS (sizeof(mutexes)/sizeof(*mutexes))

Alternatively, you can do it with code, such as:

或者,您可以使用代码来完成,例如:

#define NUM_THREADS 5
static pthread_mutex_t mutexes[NUM_THREADS];

// Other stuff

int main (void) {
    for (int i = 0; i < NUM_THREADS; i++)
        pthread_mutex_init(&mutexes[i], NULL);
    // Now you can use them safely.

    return 0;
}

In all those cases, they're correctly set up before you try to use them. In fact, I'd do it well before you do anythreading stuff but that's just me being paranoid.

在所有这些情况下,在您尝试使用它们之前,它们都已正确设置。事实上,在你做任何线程处理之前,我会做得很好,但这只是我偏执。