#include <mutex>
#include <condition_variable>
class Event {
public:
Event() {};
~Event() {};
bool wait(std::chrono::milliseconds millisec) {
std::unique_lock<std::mutex> l(m_lock);
auto cv = m_cond.wait_for(l, millisec);
if (cv == std::cv_status::no_timeout) {
return true;
}
return false;
};
void notify() {
m_cond.notify_all();
};
private:
std::mutex m_lock;
std::condition_variable m_cond;
};
class MyClass
{
public:
MyClass() {};
~MyClass() {};
void start() {
std::thread run_thread(std::bind(&MyClass::run, this));
run_thread.detach();
};
void run() {
while (true)
{
if (m_event.wait(std::chrono::milliseconds(500)))
{
printf("end thread!\n");
break;
}
else
{
printf("do something,continue thread!\n");
continue;
}
}
};
void stop() {
m_event.notify();
};
private:
Event m_event;
};
int main()
{
MyClass test;
test.start();
std::this_thread::sleep_for(std::chrono::milliseconds(1000*10));
printf("before stop!\n");
test.stop();
system("pause");
return 0;
}
上面这段代码,本意是想当调用stop的时候通知线程退出,但是实际情况是不到调用stop之前,线程就被通知退出了。而且退出时机是随机的,有时早有时晚,可能是我对condition_variable理解的不够,请问哪里的问题。谢谢
--
FROM 124.126.202.*