3

I'm trying to implement a program using Pthreads in C. Now, I've tried to let a single thread print "Hi":

void * generator(void *arguments){
     printf("Hi");
     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!

Steven
  • 1,123
  • 5
  • 14
  • 31
  • 1
    Add a newline to the output format. Messages don't appear otherwise (unless you flush them). And use `int main(void)` when you're ignoring the command line arguments. – Jonathan Leffler Nov 09 '16 at 19:09

1 Answers1

7

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.

2501
  • 25,460
  • 4
  • 47
  • 87
P.P
  • 117,907
  • 20
  • 175
  • 238