Steven Raaijmakers Steven Raaijmakers - 9 months ago 72
C Question

Print in single Pthread

I'm trying to implement something a program with Pthreads in C. Now, I'm trying to let a single thread print something:

void * generator(void *arguments){
return NULL;

int main(int argc, const char* argv[]){
pthread_create(&threads_ids[0], NULL, &generator, NULL);=

This doesn't work and doesn't print anything. However, when I put the creation of the pthread in a for loop it does print "Hi", but at each execution the occurrence differs.

Is this normal behaviour, and if so; how can I fix it? Thanks in advance!

Answer Source

It's because your main thread returns and thus exits the process. It means the thread you created never gets a chance to run.

Unlike just returning from main(), calling pthread_exit(0) from main(), will let the other thread continue executing.

Alternatively, you can wait for the thread to complete execution by calling pthread_join() on the thread you created.

When you execute in a loop, probably some of the threads you create gets executed before main thread exits, and thus appears to "work" (prints some Hi). But it does have the same problem as the code you posted.