C++ 等待线程退出

标签 c++ multithreading termination

我在 Linux 下用 C++ 写了一个程序。对于线程,我使用的是 pthread。 在程序中,我启动线程并且该线程一直运行,直到我调用该函数,该函数应该停止它。在这里你可以看到我的代码。

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);
}

当线程启动时,它会做 smth。直到 isRunning 的值为 false 并且主程序本身会做其他事情。问题是,当我调用函数 stopThread 时,该函数只是将 isRunning 设置为 false,而不是等待线程在 while 循环内完成其任务。 我的问题是,我如何告诉函数 stopThread,它应该等待线程退出。

在将 isRunning 设置为 false 后,我尝试将 pthread_join 放入 stopThread 函数中。但有时它会导致问题,即程序无限等待。因为线程完成得比程序来等待线程更快。因为线程可以位于 while 循环内的不同部分。所以我永远不知道线程需要退出多少。

谢谢

最佳答案

根据我对你问题的理解,你应该使用 thread joining 的概念.

像这样,

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;
}

关于C++ 等待线程退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6669033/

相关文章:

c++ - 从指针调用重载运算符

c++ - 尝试将整数强制转换为 void 以按值传递给 pthread 函数

c# - 如何等待已结束的IObserver调用,包括观察订户调用?

c++ - 如何正确关闭与 Poco::HTTPSClientSession 的连接?

c++ - 访问结构内容,当不同 DLL 的类型及其内容不同时

c++ - 带有结构指针数组的getline

c# - 如何在lua cpp模块中调用托管c++ dll函数

c - 用 C 语言实现多线程按键事件

android - 如何以编程方式强制停止我的 Android 应用程序?

ASP.NET Web 服务器在 HTTPS 方面存在问题——仅限 Chrome