#include <iostream>
#include <thread>
#include <mutex>
#include <atomic>
#include <chrono>
#include <condition_variable>
class example
{
::std::thread m_thread;
::std::mutex m_mutex;
::std::condition_variable m_cond;
bool m_loop;
int m_counter;
private: void start(void)
{
m_loop = true;
m_thread = ::std::thread{&example::thread_routine, this};
}
private: void thread_routine(void)
{
::std::unique_lock lock{m_mutex};
do
{
::std::cout << m_counter << ::std::endl;
}
while
(
not m_cond.wait_for
(
lock
, ::std::chrono::seconds{1}
, [this](void)
{
return not m_loop;
}
)
);
}
private: void stop(void)
{
{
::std::lock_guard lock{m_mutex};
m_loop = false;
}
m_cond.notify_one();
m_thread.join();
++m_counter;
}
public: example(void): m_loop{}, m_counter{}
{
start();
}
public: ~example(void)
{
stop();
}
public: void restart(void)
{
stop();
start();
}
};
int main()
{
example ex{};
for (;;)
{
::std::this_thread::sleep_for(::std::chrono::seconds{3});
ex.restart();
}
return 0;
}