#include <thread> int main() { std::thread ft(SendRecv); } void SendRecv(){ while (true); }
I know, a not very useful code was written ... But I need to figure out how to terminate the stream if it did not complete after 5 seconds
#include <thread> int main() { std::thread ft(SendRecv); } void SendRecv(){ while (true); }
I know, a not very useful code was written ... But I need to figure out how to terminate the stream if it did not complete after 5 seconds
Example:
#include <thread> #include <chrono> #include <future> using namespace std::chrono_literals; class stoppable { public: stoppable() : m_termination_signal() , m_future(m_termination_signal.get_future()) {} stoppable(stoppable&& obj) noexcept : m_termination_signal(std::move(obj.m_termination_signal)) , m_future(std::move(obj.m_future)) {} stoppable& operator=(stoppable&& obj) noexcept { if (this != &obj) { m_termination_signal = std::move(obj.m_termination_signal); m_future = std::move(obj.m_future); } return *this; } virtual void run() = 0; bool stopping() { if (m_future.wait_for(1ms) == std::future_status::timeout) return false; return true; } void stop() { m_termination_signal.set_value(); } protected: std::promise<void> m_termination_signal; std::future<void> m_future; }; class task: public stoppable { public: void run() override { while (not stopping()) std::this_thread::sleep_for(1s); } }; int main() { task task; std::thread th {[&]() { task.run(); }}; std::this_thread::sleep_for(5s); task.stop(); th.join(); return 0; }
Source: https://ru.stackoverflow.com/questions/969444/
All Articles
native_handle()
and the operating system API ... - Harry