Search code examples
cpthreadspthread-join

main() does not terminate after successful pthread_join


I have a program that starts a pthread and later on waits for the termination of this thread before it returns. The code is something like:

int main(int32_t argc, char* argv[]) {
  pthread_t t;
  /* initialization and other stuff 
     ... 
  */
  printf("join result:%d\n", pthread_join(t, 0));
  return 0;
}

The program prints, as it is supposed to: join result: 0. So the join works and t is finished. Nevertheless the program does not stop execution. I can only force it to stop if I insert a command exit(0) (or some other number) before the return 0 line.

However, if I remove the line with the pthread_join call the program exits flawlessly.

How is this even possible? What could keep a program from finishing execution after all sub-threads are joined?

EDIT: I just found out that gdb tells me I get a segmentation fault after the execution of the last line with }. Nevertheless I have no idea what is going on behind the scenes:

Program received signal SIGSEGV, Segmentation fault.
0x000000060003aa10 in ?? ()

Solution

  • I think it may be possible that a stack corruption occurs in the main thread. From windows i know that before executing main, the adress of the exit_process function is pushed onto the stack. Then return 0 performs an exit_process call. If in your case the stack was corrupted, it's possible the pointer to exit_process was replaced with an invalid pointer.