Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does function return type need to be of type (void*) for threading in C?

In c, we create a thread like so:

void * run(void * arg){
    printf("hello world\n");
}

int main(){
    pthread_t thread;
    int a = pthread_create(&thread, NULL, run, (void*)0);
}

But it will not work if I declare run as

void run(){}

On the other hand, if I cast it to (void *) in the parameter of pthread_create, it works fine. So it only accepts functions with return types of (void *).

Why?

Thanks !

like image 376
Kira Avatar asked Jan 16 '23 18:01

Kira


1 Answers

The thread function must be declared to return void * because the threading library expects such a return value, and will store it into a location given to pthread_join() after the thread terminates.

If you don't need the thread return value for anything, you can just return 0;.

like image 149
caf Avatar answered Feb 14 '23 15:02

caf