Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the function pointer to a function in C?

Tags:

c

pthreads

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();

like image 378
ratzip Avatar asked Jan 08 '23 14:01

ratzip


1 Answers

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);
like image 134
Lundin Avatar answered Jan 18 '23 23:01

Lundin