gpt4 book ai didi

c++ - 这种使用指向实例的指针创建分离的 std::thread 的方法是否错误?

转载 作者:行者123 更新时间:2023-11-30 03:18:58 26 4
gpt4 key购买 nike

我遇到过一些类,它们的唯一功能是在一个循环中不断地做一些工作,它们被设计成定义了一个公共(public)方法,可以调用该方法以在新的 std::中调用此成员函数。线程。我指的是这样的东西:

class ThreadLooper {
public:
ThreadLooper(const std::string &thread_name)
: thread_name_{thread_name}, loopCounter_{0} {}

~ThreadLooper() {
cout << thread_name_ << ": destroyed and counter is " << loopCounter_
<< std::endl;
}

void run() {
std::thread([this]() { detachedThreadLoop(); }).detach();
}

private:
void detachedThreadLoop() {
cout << thread_name_ << ": detachedThreadLoop() started running"
<< std::endl;
while (true) {
using namespace std::literals::chrono_literals;
std::this_thread::sleep_for(2s);
++loopCounter_;
cout << thread_name_ << ": counter is " << loopCounter_ << std::endl;
}
}

std::string thread_name_;
std::atomic_uint64_t loopCounter_;
};

int main() {
cout << "In main()" << std::endl;
{
ThreadLooper threadLooper{"looper1"};
threadLooper.run();
using namespace std::literals::chrono_literals;
std::this_thread::sleep_for(20s);
cout << "main() done sleeping, exiting block scope..." << std::endl;
}

while (true) {
using namespace std::literals::chrono_literals;
std::this_thread::sleep_for(20s);
cout << "main() woke up..." << std::endl;
}

return 0;
}

似乎因为在分离线程中运行的函数有一个指向实例的指针,但可以在该实例的生命周期之后继续运行,这是不好的。我已经看到其他线程没有分离的类,然后在析构函数中设置一个标志来告诉线程循环退出,然后将线程加入析构函数。似乎后者是执行此操作的正确方法,而前者依赖于这样一个事实,即该类将仅在其实例在程序运行期间存在的情况下使用。这是正确的还是我遗漏了什么?

最佳答案

是的,使用 std::thread::detach 意味着您需要有自己的方法来确保线程在它使用的所有资源被销毁之前终止。

在这种情况下,当程序退出 main() 中的第一个 block 作用域时,ThreadLooper 将调用未定义的行为。最好不要使用 detach(),如果您忘记调用 std::thread 将调用 std::terminate join() 在线程(及其包含的对象)被销毁之前。

关于c++ - 这种使用指向实例的指针创建分离的 std::thread 的方法是否错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54172526/

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