我有一个C语言函数:
void start_fun()
{
// do something
}
我想使用 pthread_create()
创建一个线程,并且启动例程为 start_fun()
,不修改 void start_fun()
的情况下,如何获得指向 start_fun()
的函数指针。
如果您在代码中任何地方写下没有参数的函数名start_fun
,则会获得指向该函数的函数指针。
然而,pthread_create期望一个格式为void* func (void*)
的函数。
如果重写函数不是一种选择,那么您将不得不编写一个包装器:
void* call_start_fun (void* dummy)
{
(void)dummy;
start_fun();
return 0;
}
然后将 call_start_fun 传递给 pthread_create:
pthread_create(&thread, NULL, call_start_fun, NULL);
pthread_create
所需的正确类型。 - ArjunShankarcall_start_fun
返回NULL
。 - JeremyP(void*)0
。 - Lundinpthread_create()
的签名要求如此,如果您不提供它,则您的程序具有未定义的行为,可能涉及崩溃或内存损坏。 - John Bollinger函数名称作为表达式使用时,将计算为指向命名函数的指针。例如:
pthread_t thread_id;
int result = pthread_create(&thread_id, NULL, start_fun, NULL);
然而,您提供的start函数没有正确的签名,因此将其用作pthread start函数会产生未定义的行为。start函数必须具有以下签名:
void *start_fun(void *arg);
NULL
(如果适用的话),但必须声明参数和返回值(具有这些类型)。
start_fun
是指向start_fun
的指针。但是它不是正确类型的函数。pthread_create
需要一个void * (*f) (void *)
。 - ArjunShankar