静态pthread互斥锁初始化 [英] Static pthreads mutex initialization
问题描述
使用pthread,如何在C中初始化静态的互斥数组?
Using pthreads, how would one, in C, initialize a static array of mutexes?
对于单个静态互斥锁,似乎可以使用PTHREAD_MUTEX_INITIALIZER.但是它们的静态数组呢?例如,
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,
#include <pthread.h>
#define NUM_THREADS 5
/*initialize static mutex array*/
static pthread_mutex_t mutexes[NUM_THREADS] = ...?
还是必须动态分配它们?
Or must they be allocated dynamically?
推荐答案
If you have a C99 conforming compiler you can use P99 to do your initialization:
static pthread_mutex_t mutexes[NUM_THREADS] =
{ P99_DUPL(NUM_THREADS, PTHREAD_MUTEX_INITIALIZER) };
这只是将令牌序列PTHREAD_MUTEX_INITIALIZER,
重复请求的次数.
This just repeats the token sequence PTHREAD_MUTEX_INITIALIZER,
the requested number of times.
为此,您只需确保NUM_THREADS
不会扩展为变量,而是扩展为预处理器可见的十进制整数常数,并且该常数不会太大.
For this to work you only have to be sure that NUM_THREADS
doesn't expand to a variable but to a decimal integer constant that is visible to the preprocessor and that is not too large.
这篇关于静态pthread互斥锁初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!