一、下面主要了解四个函数的作用
1、get_id() 获取线程ID
2、sleep_for() 延时时间函数
3、yield() 让线程放弃执行,让操作系统调用另一个线程
4、sleep_until() 获取当前系统传转换本地时间,阻塞线程
#include<thread>
#include<ctime>
#include<chrono>
#include<iostream>
#include<time>
#include<iomanip>
using namespace std;
using namespace this_thread;
/*
1、get_id() 获取线程ID
2、sleep_for() 延时时间函数
3、yield() 让线程放弃执行,让操作系统调用另一个线程
4、sleep_until() 获取当前系统传转换本地时间,阻塞线程
*/
//1、get_id() 获取线程ID
void threadFunc()
{
cout<<"线程ID:"<<this_thread::get_id()<<endl;
}
//2、sleep_for() 延时时间函数
void threadSleep_for()
{
cout<<"线程ID:"<<this_thread::get_id()<<"线程启动"<<endl;
this_thread::sleep_for(5s);
this_thread::sleep_for(chrono::seconds(100));
cout<<"线程ID:"<<this_thread::get_id()<<"线程结束"<<endl;
}
//3、yield() 让线程放弃执行,让操作系统调用另一个线程执行
void threadYield(chrono::microseconds duration)
{
cout<<"线程ID:"<<this_thread::get_id()<<"线程启动"<<endl;
auto startTime = chrono::high_resolution_clock::now(); //当前系统时间
auto endTime = starTime + duration; //结束时间
do
{
this_thread::yield();
/*
需要实现其他功能,写在里面即可
*/
cout<<1<<endl;
}while(chrono::high_resolution_clock::now() < endTime);
cout<<"线程ID:"<<this_thread::get_id()<<"线程结束"<<endl;
}
//4、获取当前系统传转换本地时间,阻塞线程
void threadSleep_until()
{
time_t cP = chrono::system_clock::to_time_t(chrono::system_clock::now());
tm *ptm = new tm;
localtime_s(ptm,&t);
if(!ptm != nullptr)
{
this_thread::sleep_until(chrono::system_clock::from_time_t(mktime(ptm)));
}
cout<<put_time(ptm,"%X")<<endl;
}
int main()
{
cout<<"主线线程ID:"<<this_thread::get_id()<<endl;
thread t1(threadFunc);
t1.join();
thread t2(threadSleep_for);
t2.join();
thread test(threadYield,chrono::microseconds(100));
test.join();
threadSleep_until();
return 0;
}