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