lichao
2021-06-03 8967e7f2f8b94dc032135707e16c8a9f233d0db6
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
/*
 * =====================================================================================
 *
 *       Filename:  robust.cpp
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2021年04月27日 10时04分19秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Li Chao (), lichao@aiotlink.com
 *   Organization:  
 *
 * =====================================================================================
 */
#include "robust.h"
#include <thread>
 
using namespace std::chrono;
using namespace std::chrono_literals;
 
namespace
{
void yield() { std::this_thread::sleep_for(10us); }
} // namespace
 
namespace robust
{
 
bool AtomicReqRep::ClientRequest(const Data request, Data &reply)
{
    auto end_time = now() + 3s;
    do {
        Data cur = data_.load();
        if (GetState(cur) == eStateFree &&
            DataCas(cur, Encode(request, eStateRequest))) {
            do {
                yield();
                cur = data_.load();
                if (GetState(cur) == eStateReply) {
                    DataCas(cur, Encode(0, eStateFree));
                    reply = Decode(cur);
                    return true;
                }
            } while (now() < end_time);
        }
        yield();
    } while (now() < end_time);
    return false;
}
 
bool AtomicReqRep::ServerProcess(Handler onReq)
{
    Data cur = data_.load();
    switch (GetState(cur)) {
    case eStateRequest:
        if (DataCas(cur, Encode(onReq(Decode(cur)), eStateReply))) {
            timestamp_ = now();
            return true;
        }
        break;
    case eStateReply:
        if (timestamp_.load() + 3s < now()) {
            DataCas(cur, Encode(0, eStateFree));
        }
        break;
    case eStateFree:
    default: break;
    }
    return false;
}
} // namespace robust