#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

  • one
    By means of the operating system, for example. But it is better not to kill the flow by force - this is violence against resources, for example, over interrupted logic ... It would be better to rewrite it so that it ends itself. - Harry
  • @Harry is not possible to do. Because y me ZMQ sometimes freezes. In order and saw as an emergency switch - Alrott SlimRG
  • 2
    Well, then I would (with the understanding of all the problems) use native_handle() and the operating system API ... - Harry
  • @Harry I do not use the operating system API - Alrott SlimRG
  • @Harry can i do without this? - Alrott SlimRG

1 answer 1

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; } 

Run an example in wandbox