【发布时间】:2011-10-03 20:02:33
【问题描述】:
我有一个程序启动一个线程(使用 pthreads),该线程将为程序的其余部分执行一些后台任务。主程序在终端中运行,一个常见的用例是在它自己退出之前使用 Ctrl-C 关闭它。有人要求我改变我产生成为僵尸的线程。我以前没有考虑过这个问题,而且我一般是多线程编程的新手。我创建了一个我希望的小而完整且独立的测试程序,它应该模仿真实程序的行为。
在下面的代码中,产生的线程是否有变成僵尸的风险?回想一下,可以使用 Ctrl-C 杀死程序,也许这是一种特殊情况,我不确定。
现在,在 MyThread 对象被删除后,线程继续运行。这不是一个真正的问题,因为在实际程序中,MyThread 对象在程序即将退出时被销毁。我只想知道,在父线程消失后,线程永远不会有成为系统僵尸的风险。
我想我可以有一个受互斥保护的变量,我在每次迭代时检查线程 func 以告诉我是否应该退出,我可以在 MyThread 析构函数中将此变量设置为 true,但也许我不需要要做到这一点? 抱歉,有点长,感谢阅读并提前感谢您的帮助!
#include <iostream>
#include <pthread.h>
#include <unistd.h>
class MyThread
{
public:
MyThread() : is_running(false) {}
void Run()
{
if (!is_running) {
if (pthread_create(&thread, NULL,
(void * (*)(void *))RunThread,
NULL) == 0) {
is_running = true;
}
else {
std::cerr << "pthread_create() failed." << std::endl;
}
}
else {
std::cout << "The thread was already running." << std::endl;
}
}
private:
static void * RunThread(void */*arg*/)
{
while (true) {
sleep(1);
std::cout << "Hello from RunThread" << std::endl;
}
return NULL;
}
pthread_t thread;
bool is_running;
};
int main()
{
MyThread *thread = new MyThread;
thread->Run();
std::cout << "Going to sleep for five seconds." << std::endl;
sleep(5);
std::cout << "No longer asleep, deleting thread object." << std::endl;
delete thread;
std::cout << "Hit enter to exit program." << std::endl;
std::cin.get();
return 0;
}
【问题讨论】:
-
感谢大家的帮助,快速而简洁。我希望我完成了我应该完成的 stackoverflow 职责。
-
如果父进程消失,进程不会成为僵尸进程。如果父进程死了,该进程将立即由 init (pid 1) 继承,并在完成时获得。一个进程只有在它的父进程还活着的时候终止并且父进程没有收获它(通过 wait() 或 waitpid())才会成为僵尸。
-
感谢 Pursell 先生的有益评论!