gpt4 book ai didi

c++ - 这个线程会变成僵尸吗

转载 作者:IT王子 更新时间:2023-10-29 00:31:58 26 4
gpt4 key购买 nike

我有一个启动线程(使用 pthreads)的程序,该线程将为程序的其余部分执行一些后台任务。主程序在终端中运行,一个常见的用例是在使用 Ctrl-C 自行退出之前关闭它。有人让我改变我生成的线程成为僵尸。我以前没有想过这个问题,而且我总体上是多线程编程的新手。我创建了一个小而完整的独立测试程序,我希望它能模仿真实程序的行为。

在下面的代码中,生成的线程是否有变成僵尸的风险?回想一下,该程序可以使用 Ctrl-C 终止,也许这是一种特殊情况,我不确定。

此时,线程在 MyThread 对象被删除后继续运行。这并不是真正的问题,因为在实际程序中,MyThread 对象无论如何都会在程序即将退出时被销毁。我只是想知道,在父进程消失后,线程永远不会有成为系统僵尸的风险。

我想我可以有一个互斥保护变量,我在每次迭代时检查线程函数以告诉我是否应该退出,我可以在 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;
}

最佳答案

线程不会变成僵尸;过程做。当您终止一个进程时,这会自动终止它的所有线程。

简而言之,您不需要做任何特别的事情,因为您有第二个线程正在运行。

关于c++ - 这个线程会变成僵尸吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7640059/

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