timed_mutex
constructor
constexpr timed_mutex() no_exception; //object unlock state
timed_mutex(const timed_mutex&) = delete; //不能拷贝或移动拷贝
构建过程不是原子操作,所以在构建过程可能会出现data race;
void lock(); void unlock(); bool try_lock();
和mutex的lock/unlock/tyr_lock同;
try_lock_for
template<class Rep, class Period>
bool try_lock_for(const chrono::duration<Rep, Period>& rel_time);
rel_time
当前线程阻塞,等待获得一个锁的最大时间,如果可以获得则返回true,否则返回false;
duration表示一个具体的相对的时间
try_lock_until
template<class Clock, class Duration>
bool try_lock_until(const chrono::time_point<Clock, Duration>& abs_time);
其他两种情况同mutex,其中第二种情况,如果有其他线程占用mutex,execution of the calling thread is blocked until unlocked or until abs_time
abs_time
指一个时间点,这个时间点,调用线程将停止阻塞,不再尝试去lock
time_point代表一个具体的绝对时间;
recursive_timed_mutex
recursive_timed_mutex::
try_lock_for
try_lock_until
try_lock
lock
unlock
兼有timed_mutex和recursive_mutex功能;
// timed_mutex::try_lock_until example
#include <iostream> // std::cout
#include <chrono> // std::chrono::system_clock
#include <thread> // std::thread
#include <mutex> // std::timed_mutex
#include <ctime> // std::time_t, std::tm, std::localtime, std::mktime
std::timed_mutex cinderella;
// gets time_point for next midnight:
std::chrono::time_point<std::chrono::system_clock> midnight() {
using std::chrono::system_clock;
std::time_t tt = system_clock::to_time_t (system_clock::now());
struct std::tm * ptm = std::localtime(&tt);
++ptm->tm_mday; ptm->tm_hour=0; ptm->tm_min=0; ptm->tm_sec=0;
return system_clock::from_time_t (mktime(ptm));
}
void carriage() {
if (cinderella.try_lock_until(midnight())) {
std::cout << "ride back home on carriage\n";
cinderella.unlock();
}
else
std::cout << "carriage reverts to pumpkin\n";
}
void ball() {
cinderella.lock();
std::cout << "at the ball...\n";
cinderella.unlock();
}
int main ()
{
std::thread th1 (ball);
std::thread th2 (carriage);
th1.join();
th2.join();
return 0;
}