Search code examples
c++multithreadingtermination

c++ waiting for thread exit


I wrote a program in C++ under Linux. For thread I am using pthread. In the program I start the thread and this thread is running until I call the function, that should stop it. Here you can see my code.

bool isRunning = false;
pthread_t thread;

void startThread() {
    isRunning = true;
    int thread_return = pthread_create(&thread, NULL, runThread, NULL);
}

bool stopThread() {
    isRunning = false;
    // wait until the thread will be finished
    return true;
}

void* runThread(void* ptr) {
    while(isRunning) {
        // do smth.
    }
    pthread_exit(NULL);
}

When the thread was started, it will do smth. until the value of isRunning will be false and the main program itself will do other stuff. The problem is, when I call the function stopThread, this function just sets isRunning to false and not waiting until the thread will finish its task inside the while-loop. My question is, how I can say to function stopThread, that it should wait for thread exit.

I tried to put pthread_join in stopThread function after I set isRunning to false. But sometimes it causes the problem, that the program waits infinitly. Because the thread was finished faster, than the program comes to wait for thread. Because the thread can be on different parts inside the while-loop. So I never know how much the thread need to exit.

Thank you


Solution

  • From what I understand in your question, you should be using the concept of thread joining.

    Like so,

    bool stopThread() {
        int returnCode;
        isRunning = false;
        void *status;
        rc = pthread_join(your_thread, &status);
    
        // wait until the thread will be finished
    
        if (rc) {
            printf("ERROR; return code from pthread_join() 
                    is %d\n", rc);
            exit(-1);
        }
        printf("Main: completed join with thread %ld having a status   
                of %ld\n",t,(long)status);
    
        return true;
    }