【发布时间】:2023-01-31 17:18:00
【问题描述】:
我在使用重新启动函数退出线程时遇到问题。当调用 Stop 时它退出线程,但是 Restart 调用 Stop 然后在之后立即开始 - 不退出线程 - >调用 Start 并创建一个新线程。
谢谢。任何帮助都会非常有帮助和感激。
显示问题的虚拟代码:
#include <iostream>
#include <thread>
#include <condition_variable>
#include <chrono>
using namespace std;
bool running = false;
unsigned int interval = 5000;
condition_variable cv_work;
mutex mu_cv_work;
void Start()
{
unique_lock<std::mutex> lock(mu_cv_work);
running = true;
lock.unlock();
thread([]{
cout << "new thread" << '\n';
while (running)
{
cout << "work..." << '\n';
unique_lock<std::mutex> lock(mu_cv_work);
cout << "sleep" << '\n';
if (cv_work.wait_for(lock, chrono::milliseconds(interval), []{return running == false;}))
{
cout << "exit thread" << '\n';
return;
}
cout << "done sleeping" << '\n';
}
}).detach();
}
void Stop()
{
unique_lock<std::mutex> lock(mu_cv_work);
running = false;
lock.unlock();
cv_work.notify_one();
}
void Restart()
{
Stop();
Start();
}
int main()
{
Start();
cout << "press to Stop" << '\n';
cin.get();
Stop(); // Stop actually exits the Thread
cout << "press to Start" << '\n';
cin.get();
Start();
cout << "press to Restart" << '\n';
cin.get();
Restart(); // Stop doesn't exit the Thread (Restart calls Stop() and Start())
return 0;
}
输出:
press to Stop
new thread
work...
sleep
// KEY PRESS
exit thread
press to Start
// KEY PRESS
new thread
work...
sleep
press to Restart
// KEY PRESS
new thread
work...
sleep
done sleeping
work...
sleep
预期输出:
press to Stop
new thread
work...
sleep
// KEY PRESS
exit thread
press to Start
// KEY PRESS
new thread
work...
sleep
press to Restart
// KEY PRESS
exit thread // THIS LINE
new thread
work...
sleep
done sleeping
work...
sleep
【问题讨论】:
-
当您调用
Stop()时,您如何知道线程何时结束?在你开始新的之前,你怎么知道它已经结束了?如果两个线程同时运行,哪个线程收到条件?可以肯定的是,你不应该detach它,这样你就可以在Stop()中join它。 -
除此之外,什么会阻止某人做
Start(); Start();?它提出从一开始就存在重大的设计问题。 -
@WhozCraig 这只是代码的虚拟版本。我明白了,不用担心 ;) 但还是谢谢
-
@Scheff'sCat 我添加了 if joinable() then join() 并且它输出了预期的输出,但是在那之后因为“没有活动异常而终止调用”而立即崩溃
-
旁注:关于
using namespace std...
标签: c++ multithreading timer restart conditional-variable