静态 pthread 互斥体初始化
使用 pthreads,在 C 语言中如何初始化互斥体的静态数组?
对于单个静态互斥体,我似乎可以使用 PTHREAD_MUTEX_INITIALIZER 。但是它们的静态数组又如何呢?例如,
#include <pthread.h> #define NUM_THREADS 5 /*initialize static mutex array*/ static pthread_mutex_t mutexes[NUM_THREADS] = ...?
或者它们必须动态分配吗?
Using pthreads, how would one, in C, initialize a static array of mutexes?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,您不必动态创建它们。您可以使用静态数组,只需在使用它们之前将它们全部设置好即可。你可以这样做:
如果你改变
NUM_THREADS
,这很容易出错,尽管这可以用类似的东西来修复:或者,你可以用代码来做到这一点,例如:
在所有这些情况下,他们'在尝试使用它们之前请先正确设置。事实上,我会在你做任何线程的事情之前就做好,但这只是我的偏执。
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:
which is prone to errors if you ever change
NUM_THREADS
, though that can be fixed with something like:Alternatively, you can do it with code, such as:
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 any threading stuff but that's just me being paranoid.
如果您有符合 C99 标准的编译器,则可以使用 P99 进行初始化:
这只是重复令牌序列
PTHREAD_MUTEX_INITIALIZER
所请求的次数。为此,您只需确保
NUM_THREADS
不会扩展为变量,而是扩展为预处理器可见且不太大的十进制整数常量。If you have a C99 conforming compiler you can use P99 to do your initialization:
This just repeats the token sequence
PTHREAD_MUTEX_INITIALIZER,
the requested number of times.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.