I have a function in C:
void start_fun()
{
// do something
}
I want to use pthread_create()
to create a thread and the start routine is start_fun()
, without modifing void start_fun()
, how to get the function pointer to start_fun()
;
I have a function in C:
void start_fun()
{
// do something
}
I want to use pthread_create()
to create a thread and the start routine is start_fun()
, without modifing void start_fun()
, how to get the function pointer to start_fun()
;
If you write the function name start_fun
without any parameters anywhere in your code, you will get a function pointer to that function.
However pthread_create expects a function of the format void* func (void*)
.
If rewriting the function isn't an option, you'll have to write a wrapper:
void* call_start_fun (void* dummy)
{
(void)dummy;
start_fun();
return 0;
}
then pass call_start_fun to pthread_create:
pthread_create(&thread, NULL, call_start_fun, NULL);
The function name, used as an expression, evaluates to a pointer to the named function. Thus, for instance:
pthread_t thread_id;
int result = pthread_create(&thread_id, NULL, start_fun, NULL);
HOWEVER, the start function you present does not have the correct signature, therefore using it as a pthread start function produces undefined behavior. The start function must have this signature:
void *start_fun(void *arg);
The function may ignore its argument and always return NULL
, if appropriate, but it must be declared with both the argument and the return value (of those types).