您当前的位置: 首页 >  c++

龚建波

暂无认证

  • 3浏览

    0关注

    312博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

C++ 多线程中有时间限制的等待

龚建波 发布时间:2019-09-26 10:17:17 ,浏览量:3

C++多线程中的一些等待函数允许设定超时。有两类可指定的超时,一是基于时间段的超时等待,一般为 _for 后缀的方法;或者绝对超时,等到一个时间点,一般为 _until 后缀的方法。例如, std::condition_variable 就具有 wait_for() 和 wait_until() 成员函数。

1.时钟

就C++标准库所关注的而言,时钟是时间信息的来源。具体来说,时钟提供四个不同部分信息的类。

  • 现在(now)时间。调用该时钟类的静态成员函数now()获取。
  • 用来表示从时钟获取到的时间值的类型。通过time_point成员的typedef来指定。
  • 时钟的节拍周期。由分数秒指定,由period成员typedef给出,每秒走25拍就具有std::ratio的period。
  • 时钟是否以均匀的速率进行计时,决定其是否为匀速(steady)时钟。如果时钟均匀速率计时且不能被调整,则称为匀速的,is_steady静态数据成员为true。

可以参照VC种steady_clock的实现:

struct system_clock
	{	// wraps GetSystemTimePreciseAsFileTime/GetSystemTimeAsFileTime
	using rep = long long;

	using period = ratio_multiply; //【3】

	using duration = chrono::duration;
	using time_point = chrono::time_point; //【2】
	static constexpr bool is_steady = false; //【4】

	_NODISCARD static time_point now() noexcept //【1】
		{	// get current time
		return (time_point(duration(_Xtime_get_ticks())));
		}

	_NODISCARD static __time64_t to_time_t(const time_point& _Time) noexcept
		{	// convert to __time64_t
		return ((__time64_t)(_Time.time_since_epoch().count()
			/ _XTIME_TICKS_PER_TIME_T));
		}

	_NODISCARD static time_point from_time_t(__time64_t _Tm) noexcept
		{	// convert from __time64_t
		return (time_point(duration(_Tm * _XTIME_TICKS_PER_TIME_T)));
		}
	};

时钟的节拍周期是由分数表示的秒来指定的,他由时钟的period成员typedef给出。如果每秒走25拍的时钟,就具有std::ratio的period。

如果时钟以均匀速率计时且不能被调整,则该时钟被成为匀速(steady)时钟,对应标准库的std::chrono::steady_clock匀速时钟。通常,std::chrono::system_clock系统时钟是不匀速的,因为时钟可以调整,可能影响now()返回值等。此外,还有std::chrono::high_resolution_clock时钟,一般是其他时钟之一的typedef。

2.时间段

时间间隔由std::chrono::duration类模板进行处理。

模板参数为计次数类型和计次周期,计次类型可以是int/double等,计次周期是一个编译期有理数常量,表示从一个计次到下一个的秒数。

如分钟 std::chrono::duration 如毫秒 std::chrono::duration

标准库预定义有基本的时间段有seconds/minutes/hours等。 在无需截断的场合,时间段转换是隐式的,反之不然。显示转换可以通过std::chrono::duration_cast实现。

	//毫秒转秒会被截断
	std::chrono::milliseconds ms(12345);
	std::chrono::seconds s = std::chrono::duration_cast(ms);
	std::cout             
关注
打赏
1655829268
查看更多评论
0.0466s