C++11 多线程 —— 同步操作之定时等待

两种方式)There are two sorts of timeouts you may wish to specify: a duration-based timeout, where you wait for a specific amount of time (for example, 30 milliseconds), or an absolute timeout, where you wait until a specific point in time (for example, 17:30:15.045987023 UTC on November 30, 2011). Most of the waiting functions provide variants that handle both forms of timeouts. The variants that handle the duration-based timeouts have a _for suffix, and those that handle the absolute timeouts have a _until suffix.

包含头文件:<chrono>

1. Clocks

获取当前时间点)The current time of a clock can be obtained by calling the static member function now() for that clock class; for example, std::chrono::system_clock::now() will return the current time of the system clock. The type of the time points for a particular clock is specified by the time_point member typedef, so the return type of some_clock::now() is some_clock::time_point.

滴答周期:滴答一下需要多少秒?)The tick period of the clock is specified as a fractional number of seconds, which is given by the period member typedef of the clock—a clock that ticks 25 times per second thus has a period of std::ratio<1,25>.

稳定时钟)If a clock ticks at a uniform rate (whether or not that rate matches the period) and
can’t be adjusted, the clock is said to be a steady clock. The is_steady() static data member of the clock class is true if the clock is steady and false otherwise. Typically, std::chrono::system_clock will not be steady, because the clock can be adjusted.

3种时钟)Steady clocks are important for timeout calculations, as you’ll see shortly, so the C++ Standard Library provides one in the form of std::chrono::steady_clock. The other clocks provided by the C++ Standard Library are std::chrono::system_clock, which represents the “real time” clock of the system and which provides functions for converting its time points to and from time_t values, and std::chrono::high_resolution_clock, which provides the smallest possible tick period (and thus the highest possible resolution) of all the library-supplied clocks. It may actually be a typedef to one of the other clocks.


2. Durations

Durations are handled by the std::chrono::duration<> class template.

2个模板参数:①使用什么数据类型来表示duration? ②该duration的一个unit代表多少秒?)The first template parameter is the type of the representation (such as int, long, or double), and the second is a fraction specifying how many seconds each unit of the duration represents. For example, a number of minutes stored in a short is std::chrono::duration<short, std::ratio<60,1>> .

常用别名)The Standard Library provides a set of predefined typedefs in the std::chrono namespace for various durations: nanoseconds, microseconds, milliseconds, seconds, minutes, and hours.

duration 转换)Conversion between durations is implicit where it does not require truncation of the value (so converting hours to seconds is OK, but converting seconds to hours is not). Explicit conversions can be done with std::chrono::duration_cast<>. 如,

std::chrono::milliseconds ms(54802);

std::chrono::seconds s= std::chrono::duration_cast<std::chrono::seconds>(ms);

The result is truncated rather than rounded, so s will have a value of 54 in this example.

支持算术运算)Durations support arithmetic, so you can add and subtract durations to get new durations or multiply or divide by a constant of the underlying representation type (the first template parameter).

获取一个duration有多少个unit)The count of the number of units in the duration can be obtained with the count() member function. Thus std::chrono::milliseconds(1234).count() is 1234.

基于duration的等待Duration-based waits are done with instances of std::chrono::duration<>. For example, you can wait for up to 35 milliseconds for a future to be ready:

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());

The wait functions all return a status to indicate whether the wait timed out or the waited for event occurred.
In this case, you’re waiting for a future, so the function returns std::future_status::timeout if the wait times out, std::future_status::ready if the future is ready, or std::future_status::deferred if the future’s task is deferred.
The time for a duration-based wait is measured using a steady clock internal to the library.


3. Time points

类模板及其参数)The time point for a clock is represented by an instance of the std::chrono::time_point<> class template, which specifies which clock it refers to as the first template parameter and the units of measurement (a specialization of std::chrono::duration<>) as the second template parameter. 如,std::chrono::time_point<std::chrono::system_clock, std::chrono::minutes>.

时间点的值表示与epoch的距离The value of a time point is the length of time (in multiples of the specified duration) since a specific point in time called the epoch of the clock. Typical epochs include 00:00 on January 1, 1970 and the instant when the computer running the application booted up.

获取指定时间点与epoch的距离)Although you can’t find out when the epoch is, you can get the time_since_epoch() for a given time_point. This member function returns a duration value specifying the length of time since the clock epoch to that particular time point.

支持算术运算)You can add durations and subtract durations from instances of std::chrono::time_point<> to produce new time points. You can also subtract one time point from another that shares the same clock, the result is a duration specifying the length of time between the two 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;

基于时间点的等待)When you pass the time point to a wait function that takes an absolute timeout, the wait function tracks the clock change and won’t return until the clock’s now() function returns a value later than the specified timeout. 如,

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

4. 接受定时等待的函数

接受等待定时的mutex)Plain std::mutex and std::recursive_mutex don’t support timeouts on locking, but std::timed_mutex does, as does std::recursive_timed_mutex. Both these types support try_lock_for() and try_lock_until() member functions that try to obtain the lock within a specified time period or before a specified time point.

接受定时等待的函数有如下这些:

类/名称空间 函数 返回值
std::this_thread
(namespace)
sleep_for( duration )
sleep_until( time_point)
std::condition_variable
std::condition_variable_any
wait_for(lock, duration)
wait_until(lock,time_point)
std::cv_status::timeout 、 std::cv_status::no_timeout
wait_for(lock,duration, predicate)
wait_until(lock, time_point, predicate)
bool—the return value of the predicate when awakened
std::timed_mutex
std::recursive_timed_mutex
try_lock_for(duration)
try_lock_until(time_point)
boo—true if the lock was acquired, false otherwise
std::unique_lock<TimedLockable> unique_lock(lockable, duration)
unique_lock(lockable, time_point)
try_lock_for(duration)
try_lock_until(time_point)
bool—true if the lock was acquired, false otherwise
std::future<ValueType>
std::shared_future<ValueType>
wait_for(duration)
wait_until(time_point)
std::future_status::timeout if the wait timed out;
std::future_status::ready if the future is ready
std::future_status::deferred if the future holds a deferred function that hasn’t yet started

猜你喜欢

转载自blog.csdn.net/fcku_88/article/details/88412222