C++并发编程(CH04)[clock-03]

Waiting with a time limit

两种等待时间,一种时等待多长时间然后返回,一种是等待到某这个时刻返回,std::condition_variable有对他们各有两种实现支持.

Clocks

clock是一个class.它提供以下四种信息.

  1. The time now

    std::chrono::system_clock::now()
    
  2. The type of the value used to represent the times obtained from the
    clock

  3. the tick period of the clock
    时钟频率的表示方式std::ratio<1,25>表示每秒钟tick
    25次.而std::ratio<5,2>表示2.5秒钟tick一次.

  4. Whether or not the clock ticks at a uniform rate and is thus
    considered to be a steady clock 稳定的时钟非常重要.
    std::chrono::steady_clock.

Durations

  1. 定义时间间隔

    chrono::duration<short, ratio<60,1>> s(20); // 1个单位60s,而总共为20分钟的时间间隔.
    
  2. 从大单位时间可以转换为小单位事件,小的转换为大的不行.强制转换会被截断.

    std::chrono::milliseconds ms(54802);
    std::chrono::seconds s=
      std::chrono::duration_cast<std::chrono::seconds>(ms);
    //(sai:可以使用duration_cast进行时间转换) nanoseconds, microseconds, milliseconds, seconds, minutes, and hours.可以用 
    

    There are also typedefs for all the SI ratios from std::atto
    (10–18) to std::exa (1018) (and beyond, if your platform has
    128-bit integer types) for use when specifying custom durations such
    as std::duration<double,std::centi> for a count of 1/100th of a
    second represented in a double .

  3. C++14的chrono_literals

    using namespace std::chrono_literals;
    auto one_day=24h;
    auto half_an_hour=30min;
    auto max_time_between_messages=30ms;
    
  4. 线程如何等待一段时间就返回.

    std::future<int> f=std::async(some_task);
    if(f.wait_for(std::chrono::milliseconds(35))==std::future_status::ready)
      do_something_with(f.get());
    //(如何等待线程一定时间)
    

    使用的是steady clock

Time points

auto start=std::chrono::high_resolution_clock::now();
do_something();
auto stop=std::chrono::high_resolution_clock::now();
std::cout<<"do_something() took "
   <<std::chrono::duration<double,std::chrono::seconds>(stop-start).count()
   <<" seconds"<<std::endl;
//一个时间点加上一个时间duration时下一个时间点,两个时间点相减时一个时间duration

条件变量等待直至某个时刻到来.

#include <condition_variable>
#include <mutex>
#include <chrono>

std::condition_variable cv;
bool done;
std::mutex m;

bool wait_loop()
{
  auto const timeout= std::chrono::steady_clock::now()+
    std::chrono::milliseconds(500);
  std::unique_lock<std::mutex> lk(m);
  while(!done)
    {
      if(cv.wait_until(lk,timeout)==std::cv_status::timeout)
        break;
    }
  return done;
  //使用timeout对条件变量进行等待
}

注意上面的线程,比每次if语句都等待一段时间要好.因为到了某个节点之后,就break.如果是每次都等待一段时间.如果繁忙while循环会一直运行下去.

Functions that accept timeouts

std::this_thread::sleep_for()
std::this_thread::sleep_until()

std::timed_mutex
std::recursive_timed_mutex
//try_lock_for() 
//try_lock_until()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值