命名空间std::this_thread定义了四个管理当前线程的方法:
- yield 重新安排线程时间片,允许其他程序先执行
void yield() noexcept;
- get_id 返回当前线程的id
std::this_thread::id get_id() noexcept;
- sleep_for 暂停当前线程执行一段特定时间[1]
template< class Rep, class Period >
void sleep_for( const std::chrono::duration<Rep, Period>& sleep_duration );
- sleep_until 暂停当前线程直到某个时刻
template< class Clock, class Duration >
void sleep_until( const std::chrono::time_point<Clock,Duration>& sleep_time );
线程挂起一段时间
你可能需要时间间隔的一些辅助别名:
std::chrono::nanoseconds duration</*signed integer type of at least 64 bits*/, std::nano>
std::chrono::microseconds duration</*signed integer type of at least 55 bits*/, std::micro>
std::chrono::milliseconds duration</*signed integer type of at least 45 bits*/, std::milli>
std::chrono::seconds duration</*signed integer type of at least 35 bits*/>
std::chrono::minutes duration</*signed integer type of at least 29 bits*/, std::ratio<60>>
std::chrono::hours duration</*signed integer type of at least 23 bits*/, std::ratio<3600>>
std::chrono::days (since C++20) duration</*signed integer type of at least 25 bits*/, std::ratio<86400>>
std::chrono::weeks (since C++20) duration</*signed integer type of at least 22 bits*/, std::ratio<604800>>
std::chrono::months (since C++20) duration</*signed integer type of at least 20 bits*/, std::ratio<2629746>>
std::chrono::years (since C++20) duration</*signed integer type of at least 17 bits*/, std::ratio<31556952>>
从纳秒到年均有定义。在std::thread::sleep_for这样用就可以了:
std::this_thread::sleep_for(std::chrono::nanoseconds(5));//五纳秒
为了简单,你可以定义一个别名:
using ms=std::chrono::microseconds;
std::this_thread::sleep_for(ms(5));//五毫秒!
在C++14后,有一种更加接近人类的写法:
像这样:
#include <iostream>
#include <chrono>
int main()
{
using namespace std::chrono_literals;
auto d1 = 250ms;
std::chrono::milliseconds d2 = 1s;
std::cout << "250ms = " << d1.count() << " milliseconds\n"
<< "1s = " << d2.count() << " milliseconds\n";
}
[1] 这个函数相当于:
- Windows下
Sleep(unsigned long)
(毫秒,#include <windows.h>
) - Linux下的usleep sleep
unsigned int sleep/usleep(unsigned int )
#include <unistd.h>
其实QT中的QThread静态成员:
[static] void QThread::sleep(unsigned long secs)
[static] void QThread::msleep(unsigned long msecs)
[static] void QThread::usleep(unsigned long usecs)
封装最好的还是QT平台下的,缺点是需要安装QT库。C++同样与平台无关,但是需要了解标准库是std::chrono
。