目录
线程处理函数
1.获取线程id:get_id
2.延时函数:sleep_for
3.放弃执行函数,调用另一个线程:yield
4.让当前线程休眠直到指定的时间点:sleep_until
线程处理函数
1.获取线程id:get_id
#include<iostream>
#include<thread>
#include<ctime>
#include<chrono>
using namespace std;
//using namespace this_thread; 省略用
void ThreadFunction()
{
//this_thread是一个命名空间,可以用using语法省略
cout << "id:" << this_thread::get_id()<<endl;//打印子线程的id
}
int main()
{
cout << "id:" << this_thread::get_id() << endl;//打印主线程的id
thread t1(ThreadFunction);
t1.join();
return 0;
}
2.延时函数:sleep_for
#include<iostream>
#include<thread>
#include<ctime>
#include<chrono>
using namespace std;
void ThreadFunction()
{
cout << "线程id【" << this_thread::get_id() << "】启动" << endl;
this_thread::sleep_for(2s);//延迟2s
this_thread::sleep_for(chrono::seconds(3));//延迟3s
cout << "线程id【" << this_thread::get_id() << "】结束" << endl;
}
int main()
{
thread t1(ThreadFunction);
t1.join();
return 0;
}
3.放弃执行函数,调用另一个线程:yield
打印出来有点奇怪是正常的,因为是多线程在一起打印:
#include<iostream>
#include<thread>
#include<ctime>
#include<chrono>
using namespace std;
void ThreadYield(chrono::microseconds duration)//chrono::microseconds毫秒
{
cout << "Yield线程id【" << this_thread::get_id() << "】启动" << endl;
auto startTime = chrono::high_resolution_clock::now();
auto endTime = startTime + duration;
do
{
this_thread::yield();
cout << 1 << endl;
} while (chrono::high_resolution_clock::now() < endTime);
cout << "Yield线程id【" << this_thread::get_id() << "】结束" << endl;
}
void ThreadOne()
{
cout << "线程id【" << this_thread::get_id() << "】启动" << endl;
cout << "线程id【" << this_thread::get_id() << "】结束" << endl;
}
int main()
{
thread t1(ThreadYield,chrono::microseconds(2000));
t1.detach();//用join看不出来效果
thread t2(ThreadOne);
t2.join();
return 0;
}
4.让当前线程休眠直到指定的时间点:sleep_until
#include<iostream>
#include<thread>
#include<ctime>
#include<chrono>
#include<iomanip>
using namespace std;
void ThreadYield()
{
time_t t= 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(100)); 两种写法
this_thread::sleep_until(chrono::system_clock::from_time_t(mktime(ptm)));
}
cout << put_time(ptm, "%X")<<endl;//打印时间
}
int main()
{
ThreadYield();
return 0;
}