lichao
2021-05-08 28f06bc49a4d8d69f1ea2f767863b7921d12f155
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
/*
 * =====================================================================================
 *
 *       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 <chrono>
#include <thread>
 
namespace robust
{
 
namespace
{
static_assert(sizeof(steady_clock::duration) == sizeof(int64_t));
 
auto Now() { return steady_clock::now().time_since_epoch(); }
void Yield() { std::this_thread::sleep_for(10us); }
 
} // namespace
 
void QuickSleep() { Yield(); }
 
bool FMutex::try_lock()
{
    if (flock(fd_, LOCK_EX | LOCK_NB) == 0) {
        if (mtx_.try_lock()) {
            return true;
        } else {
            flock(fd_, LOCK_UN);
        }
    }
    return false;
}
void FMutex::lock()
{
    //Note: the lock order affects performance a lot,
    // locking fd_ first is about 100 times faster than locking mtx_ first.
    flock(fd_, LOCK_EX);
    mtx_.lock();
}
void FMutex::unlock()
{
    mtx_.unlock();
    flock(fd_, LOCK_UN);
}
} // namespace robust