Waiting with a time limit
两种等待时间,一种时等待多长时间然后返回,一种是等待到某这个时刻返回,std::condition_variable有对他们各有两种实现支持.
Clocks
clock是一个class.它提供以下四种信息.
-
The time now
std::chrono::system_clock::now()
-
The type of the value used to represent the times obtained from the
clock -
the tick period of the clock
时钟频率的表示方式std::ratio<1,25>表示每秒钟tick
25次.而std::ratio<5,2>表示2.5秒钟tick一次. -
Whether or not the clock ticks at a uniform rate and is thus
considered to be a steady clock 稳定的时钟非常重要.
std::chrono::steady_clock.
Durations
-
定义时间间隔
chrono::duration<short, ratio<60,1>> s(20); // 1个单位60s,而总共为20分钟的时间间隔.
-
从大单位时间可以转换为小单位事件,小的转换为大的不行.强制转换会被截断.
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 . -
C++14的chrono_literals
using namespace std::chrono_literals; auto one_day=24h; auto half_an_hour=30min; auto max_time_between_messages=30ms;
-
线程如何等待一段时间就返回.
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()