lichao
2021-05-27 026bbfaf2b5d73a26b8e2fa49158883ef64c211b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
 * =====================================================================================
 *
 *       Filename:  io_service.cpp
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2021年05月27日 13时25分18秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Li Chao (), lichao@aiotlink.com
 *   Organization:  
 *
 * =====================================================================================
 */
#include "io_service.h"
#include <chrono>
using namespace std::chrono_literals;
 
bool IoService::Start()
{
    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;
}
 
void IoService::Stop()
{
    bool cur = true;
    if (run_.compare_exchange_strong(cur, false)) {
        if (worker_.joinable()) {
            worker_.join();
        }
    }
}