gpt4 book ai didi

C++ 等待线程退出

转载 作者:行者123 更新时间:2023-11-30 03:06:24 27 4
gpt4 key购买 nike

我在 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com