![](/img/trans.png)
[英]Is there a way, in C, to ensure a function is called only once without pthread_once?
[英]passing function as argument to pthread_once
我正在尝试使用pthread_once初始化一些代码。 但是通过调用init_routine()
{1}导致编译时警告-警告:从不兼容的指针类型传递'pthread_once'的参数2,而使用
{2}不发出任何警告
在file1.c中
int init_routine (void) {
// initialize variables
}
在file1.h中
int init_routine(void);
现在我将file1.h包含在file2.c中
在file2.c中
#include "file1.h"
pthread_once_t prog_inited = PTHREAD_ONCE_INIT;
int start() {
...
pthread_once(&prog_inited, &init_routine); <-- {1}
pthread_once(&prog_inited, (void *)init_routine); <-- {2}
...
return 0;
}
这些有什么区别?
谢谢。
(回答更新的问题)在头文件中,您需要更改:
int init_routine(void);
至
void init_routine(void);
而且对pthread_once
的调用不需要init_routine
之前的&
:
pthread_once(&prog_inited, init_routine);
但是您最初拥有的是:
pthread_once(&prog_inited, (void *)init_routine);
正如cnicutar指出的那样,它并不是严格的合法C代码,但它仍应适用于当今几乎所有常用的编译器。 例如, gcc
仅在使用-pedantic
开关时才会发出警告。
调用pthread_once的正确语法是:
int pthread_once(pthread_once_t *once_control, void (*init_routine)(void));
因此,在您的情况下,呼叫应为:
pthread_once(&prog_inited, init_routine);
实际上, (void *)
并不是必需的并且是错误的,因为(void *)
不是函数指针类型,并且按照标准,您不可以这样强制转换!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.