Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The argument of pthread function can be another function?

Tags:

c

pthreads

I know how to pass a function as an argument for another function. But I don't know if the argument of a function passed to pthread can be another function. Is this even possible?

Here is sample code that compiles OK, but doesn't work:

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

pthread_t idThread;

void aFunction(){
    while(1){
        fprintf(stderr,"I've been called!\n");
        usleep(1000000);
    }
}

void * threadFunction(void *argFunc){
    // Do here some stuff;
    // ...

    // Now call the function passed as argument
    void (*func)() = argFunc;
}    

int thread_creator(void(*f)()){
    // I want to use as argument for threadFunction the f function
    pthread_create(&idThread, NULL, threadFUnction, (void *)f);
}

int main(){
    thread_creator(aFunction);
    while(1);
    return 0;
}
like image 663
Anjz Avatar asked Dec 15 '22 19:12

Anjz


1 Answers

It can be a function pointer, if you're willing to bend rules a little. Strictly speaking a void * isn't guaranteed to be able to hold a function pointer. Something like this (untested):

void some_fun()
{
    /* ... */
}

void thread_fun(void *arg)
{
    void (*fun)() = arg;
}

pthread_create(...., (void *) some_fun);

EDIT

In your example, you also need to call the function, via the function pointer. Something like:

void (*func)() = argFunc;
funct(); /* <-- */
like image 126
cnicutar Avatar answered Jan 08 '23 23:01

cnicutar