4

I have a question about some code I'm testing to start understanding posix threads.

I have this basic code:

#include <iostream>
#include <string>
#include <sstream>
#include <pthread.h>

using namespace std;

void *printInfo(void *thid){
    long tid;
    tid =(long)thid;
    printf("Hello from thread %ld.\n",tid);
    pthread_exit(NULL);
}

int main (int argc, char const *argv[])
{
    int num =8;
    pthread_t threadlist[num];
    int rc;
    long t;
    for(t=0;t<num;t++){
        printf("Starting thread %ld\n",t);
        rc = pthread_create(&threadlist[t],NULL,printInfo,(void *)t);
        if(rc)
        {
            printf("Error creating thread");
            exit(-1);
            
        }
    }
    pthread_exit(NULL);
    return 0;
}

Very simple code, start threads and print from them, this all works wonders, except that I don't understand the last pthread_exit(NULL) before the return 0; in the end of the main method.

It seems that the main thread should not be a pthread, and should not need that! If I don't put it, the code does not work: the code compiles and executes, but I only get the "starting thread" print messages, and not the "hello from ..." messages.

So basically I want to know why is that needed.

Also, the code compiles and executes properly if I comment out the include <psthread.h>.

peterh
  • 11,875
  • 18
  • 85
  • 108
cromestant
  • 652
  • 2
  • 10
  • 21
  • 1
    You actually want `pthread_join()` to allow you to wait for all the threads you have spawned to finish. You'll find all the answers here: [pthreads in C - pthread_exit](http://stackoverflow.com/questions/3330048/pthreads-in-c-pthread-exit#3330077). – Marc Butler Mar 15 '11 at 15:00
  • 1
    I adore stackoverflow for this, The answer is so simple I had not even thought about it, thanks to all. – cromestant Mar 15 '11 at 16:07

3 Answers3

4

If you don't use pthread_exit in the main function then all created threads are terminated as main finishes, i.e. in your case before they have printed anything.

By calling pthread_exit in the main function makes main wait until all threads have completed.

From the pthread_exit man page:

The process will exit with an exit status of 0 after the last thread has been terminated. The behavior is as if the implementation called exit() with a zero argument at thread termination time.

This is referring to calling pthread_exit() from the main processes thread.

Community
  • 1
  • 1
Dave
  • 56
  • 1
  • +1 I learned something new today. More explanation or emphasis on what happens if the main thread finishes without waiting would be nice. – Martin York Mar 15 '11 at 15:29
  • Note: I have not found documentation on what should happen to threads after main() exits (so it may be undefined), but all the implementations I have used behave like you describe and all child threads are unceremoniously terminated (no unwind no nothing just stopped). – Martin York Mar 15 '11 at 15:35
  • 1
    @Martin: When main returns, the standard runtime code will call `exit()`. `exit()` is request to operating system to set the status, terminate the process and release all resources. Since it applies to whole process, all threads are stopped. (Note: I believe it *is* defined somewhere, though I don't remember where) – Jan Hudec Mar 15 '11 at 15:42
  • @Jan Hudec: I do not see anything specific about threads here. But that is because threads are not part of the standard. So even by starting threads you are heading into an area that is not standard defined. Thus you need to rely on the thread implementation to define what happens happens at exit. Remember that exit will call the the atexit() handlers (does the pthread implementation register a handler to kill or wait for the threads etc). There are a lot of things that can happen at the exit point. – Martin York Mar 15 '11 at 16:46
2

pthread_exit will only terminate the main thread, but will let other threads running until they finish their job. While if you return from main or call exit, this will force killing all threads.

Benoit Thiery
  • 6,325
  • 4
  • 22
  • 28
1

You need to join your threads. What's happening without the pthread_exit is that you have started the threads, and then main exits before it has actually run any of the threads. When main exits the program stops running (as do the threads).

Generally you'd use a pthread_join which waits until the specified thread finishes execution.

It seems that pthread_exit causes main to wait for all the threads which I wasn't aware. I'd look into that however, as it's not in the documentation (as far as I've read anyway) and may not be something you want to rely on.

Edit: also in your case you don't need to use pthread_exit at all. A thread will automatically terminate when the executed function (printInfo in your case) returns. pthread_exit allows you to terminate a thread before the executed function returns, for example, if the executed function calls another function which calls pthread_exit.

Niki Yoshiuchi
  • 16,883
  • 1
  • 35
  • 44