我正在努力重新学习 C++,目前正在玩 jthread。当我在自己的线程上调用我想要的类成员函数时,我似乎已经开始工作了。然而,该函数实际上似乎从未被调用过。我无法弄清楚我在这里缺少什么。如果有人能指出我不可避免的“学习者”错误,我将非常感激。
// 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
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
std::jthread thr_A(std::bind_front(&A::update, this)); // start the parallel process fucntion in this class
}
};
// 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
}
thr_A
被定义为 start()
中的局部变量。start()
返回时,它就会被破坏。jthread
,因此在销毁时要求停止然后join
ed。start()
在启动 thr_A
后立即返回,因此线程几乎没有机会实际运行。
一个可能的解决方案是添加
thr_A
为 class A
的成员。这意味着仅当您的 a
被销毁时(当 main()
退出时)才会调用其析构函数。