| | |
| | | * ===================================================================================== |
| | | */ |
| | | #include "io_service.h" |
| | | #include <chrono> |
| | | using namespace std::chrono_literals; |
| | | |
| | | bool IoService::Start() |
| | | IoService::IoService() : |
| | | guard_(io_.get_executor()) |
| | | { |
| | | Stop(); |
| | | bool cur = false; |
| | | if (!run_.compare_exchange_strong(cur, true)) { |
| | | return false; |
| | | } |
| | | |
| | | auto proc = [this]() { |
| | | while (run_) { |
| | | io_.run_one_for(100ms); |
| | | } |
| | | OnStop(); |
| | | }; |
| | | std::thread(proc).swap(worker_); |
| | | return true; |
| | | std::thread([this]() { io_.run(); }).swap(worker_); |
| | | } |
| | | |
| | | void IoService::Stop() |
| | | IoService::~IoService() |
| | | { |
| | | bool cur = true; |
| | | if (run_.compare_exchange_strong(cur, false)) { |
| | | if (worker_.joinable()) { |
| | | worker_.join(); |
| | | } |
| | | } |
| | | guard_.reset(); |
| | | io_.stop(); // normally not needed, but make sure run() exits. |
| | | if (worker_.joinable()) |
| | | worker_.join(); |
| | | } |