#include <chrono>
#include <iostream>
#include <thread>
#include <memory>
using namespace std::chrono_literals;
// make a wrapper around thread
// that can r
class my_thread_t
{
public:
~my_thread_t()
{
m_thread->join();
}
template<typename fn_t>
void start(fn_t&& fn)
{
// Wrap the function in a lambda expression
// of our own which will keep track of the
// state of the thread (or at least of the
// function call on that thread)
auto wrapped_fn = [&]
{
m_state = state_v::running;
fn();
m_state = state_v::stopped;
};
m_thread = std::make_unique<std::thread>(wrapped_fn);
}
bool is_running() const noexcept
{
return (m_state == state_v::running);
}
private:
enum class state_v
{
initial,
running,
stopped
};
std::atomic<state_v> m_state{ state_v::initial };
std::unique_ptr<std::thread> m_thread;
};
void show_status(const my_thread_t& thread)
{
if (thread.is_running())
{
std::cout << "thread is running\n";
}
else
{
std::cout << "thread is not running\n";
}
}
int main()
{
my_thread_t thread;
show_status(thread);
thread.start([] { std::this_thread::sleep_for(1s); });
for (std::size_t n{0ul}; n < 6; ++n)
{
show_status(thread);
std::this_thread::sleep_for(250ms);
}
return 0;
}
1条答案
按热度按时间h7appiyu1#
既然你需要向后兼容,你可以这样做。