提问人:Toff 提问时间:10/21/2023 最后编辑:Toff 更新时间:10/21/2023 访问量:59
如何在单例中正确连接()线程
How to correctly join() thread in a singleton
问:
我创建了一个简单的示例。 有一个带有两个按钮的窗口:开始和停止。
当您单击“开始操作”时:TTestThread::get().start();
当您单击“停止操作”时:TTestThread::get().stop();
TTestThread 类代码(单例):
void TTestThread::run()
{
while (_runned) {
using namespace std::chrono_literals;
std::this_thread::sleep_for(10ms);
}
}
void TTestThread::start()
{
_runned.store(true);
_testThread = std::thread(
[this]() {
run();
});
}
void TTestThread::stop()
{
_runned.store(false);
if (_testThread.joinable()) {
_testThread.join();
}
}
TTestThread::~TTestThread()
{
}
TTestThread& TTestThread::instance()
{
static TTestThread instance;
return instance;
}
TTestThread& TTestThread::get()
{
static std::once_flag flag;
std::call_once(flag, [] { instance(); });
return instance();
}
class TTestThread {
private:
std::atomic<bool> _runned;
std::thread _testThread;
private:
void run();
TTestThread() = default;
~TTestThread();
static TTestThread& instance();
protected:
public:
static TTestThread& get();
void start();
void stop();
};
如果用户按“开始”,然后按“停止”,然后关闭程序 - 一切都正确。如果用户按“开始”,然后关闭程序,则会引发异常“异常程序终止”。
如果只按下了“开始”按钮,但没有按下“停止”按钮,如何在程序结束时正确操作?
答: 暂无答案
评论
stop
atexit