将std::jthread作为方法内局部变量时,线程回调为何不执行?
问题分析与解决
核心问题:start()函数里创建的std::jthread thr_A是局部变量,函数执行完毕后该对象会立即被销毁。std::jthread的析构逻辑是自动向关联线程发送停止请求,并等待线程退出,导致你的update函数还没来得及执行就被终止了,自然看不到预期输出。
修复方案:把thr_A改为类A的成员变量,让它的生命周期和类实例绑定,只要主程序里的a对象存在,线程就不会被提前销毁。
修改后的代码:
// includes and directives #include <iostream> #include <thread> #include <functional> #include <chrono> // a class for testing stuff class A { private: int updates{ 0 }; // something to count on int tick{ 1000 }; // tick time set to 1000ms initially std::jthread thr_A; // 将线程改为类成员变量 public: void set_tick(int t) { tick = (t<1?1:t); // sanity check and set tick time } int get_updates() { return updates; // I did how many? } void update(std::stop_token st) { while (!st.stop_requested()) { // stop if they say stop updates++; // count this as an update std::cout << "Performing update " << updates << "\n"; // visually indicate something happened std::this_thread::sleep_for(std::chrono::milliseconds(tick)); // wait for tick time before doing it all again } } void start() { // start a ticking function std::cout << "Starting update thread\n"; // tell someone responsible that it's started // 给成员变量赋值,初始化线程 thr_A = std::jthread(std::bind_front(&A::update, this)); } }; // main thing int main() { std::cout << "Start main thread\n"; // say that I'm starting up A a; // make me a sandwich a.set_tick(10); // really fast(ish) a.start(); // go on, get on with it std::this_thread::sleep_for(std::chrono::milliseconds(10000)); // wait until sandwich ready std::cout << "Wake main thread and terminate\n"; // sandwich is ready, time to eat }
内容的提问来源于stack exchange,提问作者Radiobiscuit
相关产品推荐
相关产品推荐

