lichao
2021-03-29 f51636c193d032723c47343e39ff8296db350200
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
 * =====================================================================================
 *
 *       Filename:  pubsub.cpp
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2021年03月24日 18时44分13秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Li Chao (), 
 *   Organization:  
 *
 * =====================================================================================
 */
#include "pubsub.h"
#include <chrono>
 
namespace bhome_shm {
 
using namespace std::chrono_literals;
const MQId kBusQueueId = boost::uuids::string_generator()("01234567-89ab-cdef-8349-1234567890ff");
const int kMaxWorker = 16;
 
BusManager::BusManager(SharedMemory &shm):
busq_(kBusQueueId, shm, 1000),
run_(false)
{
}
    
BusManager::~BusManager()
{
    Stop();
}
 
bool BusManager::Start(const int nworker)
{
    std::lock_guard<std::mutex> guard(mutex_);
    StopNoLock();
    // start
    auto Worker = [&](){
        while (this->run_) {
            std::this_thread::sleep_for(100ms);
            BusManager &self = *this;
            BHMsg msg;
            const int timeout_ms = 100;
            if (!self.busq_.Recv(msg, timeout_ms)) {
                continue;
            }
            // handle msg;
            // type: subscribe(topic), publish(topic, data)
        }
    };
 
    run_.store(true);
    const int n = std::min(nworker, kMaxWorker);
    for (int i = 0; i < n; ++i) {
        workers_.emplace_back(Worker);
    }
    return true;
}
 
bool BusManager::Stop()
{
    std::lock_guard<std::mutex> guard(mutex_);
    return StopNoLock();
}
 
bool BusManager::StopNoLock()
{
    if (run_.exchange(false)) {
        for (auto &w: workers_) {
            if (w.joinable()) {
                w.join();
            }
        }
        return true;
    }    
    return false;
}
 
} // namespace bhome_shm