#include <iostream>
#include <thread>
#include <chrono>
#include <functional>
class Test {
public:
Test() {
}
~Test() {
Stop();
}
void Start() {
if (running_) {
return;
}
running_ = true;
work_thread_ = std::thread(&Test::WorkFunc, this);
}
void Stop() {
if (!running_) {
return;
}
running_ = false;
work_thread_.join();
}
void WorkFunc() {
int val = 1;
while (running_) {
std::cout << "hello" << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
if (val++ >= 10) {
callback_(1);
}
}
}
void RegisterCallback(std::function<void(int status)> callback) {
callback_ = callback;
}
private:
std::thread work_thread_;
bool running_ = false;
std::function<void(int status)> callback_;
};
int main(void) {
Test test;
test.RegisterCallback([&](int status) {
if (status == 1) {
test.Stop();
}
});
test.Start();
int n;
std::cin >> n;
return 0;
}
在回调函数里面调用Stop会崩溃,想知道为什么会崩溃?还有就是这种问题应该如何解?求帮助