c++多线程,timed_mutex

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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值