/*
|
* =====================================================================================
|
*
|
* 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
|