C++11/std::thread – 线程的基本用法
原创文章,作者:StubbornHuang,如若转载,请注明出处:《C++11/std::thread – 线程的基本用法》https://www.stubbornhuang.com/777/
1 获取CPU核心数量
使用std::thread::hardware_concurrency()获取当前CPU核心数量。
代码示例:
#include <iostream>
#include <thread>
int main()
{
std::cout << std::thread::hardware_concurrency() << std::endl;
getchar();
return 0;
}
2 获取当前线程ID
get_id()可用于获取当前线程的id。
代码示例:
#include <iostream>
#include <thread>
int main()
{
std::thread thread{ [] {std::cout << "线程函数被启动" << std::endl; } };
std::cout << thread.get_id() << std::endl;
thread.join();
getchar();
return 0;
}
3 线程休眠
3.1 sleep_for让当前线程休眠一段时间
#include <iostream>
#include <thread>
int main()
{
std::thread thread{ [] {std::cout << "线程函数被启动" << std::endl; } };
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << thread.get_id() << std::endl;
thread.join();
getchar();
return 0;
}
3.2 sleep_until让当前线程休眠一直到指定时间
#include <iostream>
#include <iomanip>
#include <thread>
#include <chrono>
#include <ctime>
#pragma warning(disable:4996)//加上可去掉unsafe 请使用localtime_s的编译报错
int main()
{
std::thread thread{ [] {std::cout << "线程函数被启动" << std::endl; } };
std::time_t tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
struct std::tm * ptm = std::localtime(&tt);
std::cout << "当前时间为: " << std::put_time(ptm, "%X") << std::endl;
// 设定线程被唤醒时间为1分钟后
ptm->tm_min += 1;
std::this_thread::sleep_until(std::chrono::system_clock::from_time_t(mktime(ptm)));
std::cout << thread.get_id() << std::endl;
std::cout << "线程重新被唤起时间为:" << std::put_time(ptm, "%X") << std::endl;;
thread.join();
getchar();
return 0;
}
4 yield
yield放弃当前线程执行,回到准备状态,重新分配cpu资源。所以调用该方法后,可能执行其他线程,也可能还是执行该线程。
#include <iostream>
#include <thread>
#include <chrono>
int main()
{
bool ready = false;
std::thread thread{ [&] {
while (!ready)
{
std::cout << "线程函数被挂起" << std::endl;
std::this_thread::yield();
ready = true;
}
std::cout << "线程函数被启动" << std::endl;
} };
thread.join();
getchar();
return 0;
}
当前分类随机文章推荐
- C++ - 线程安全的std::cout
- C++11/std::condition_variable - 生产者消费者模型
- C++ - 使用Websocket++编写客户端连接WebSocket服务器并进行通信
- C++ - std::string输出双引号到字符串
- C++ 回调函数
- C++ - 使用C++标准库过滤Windows文件名中的非法字符
- C++ - queue存储动态指针时正确释放内存
- C++ - vector存储动态指针时正确释放内存
- C++ - int转string方法总结
- C++11 - override关键字简要介绍
全站随机文章推荐
- 资源分享 - Qt5.9 c++开发指南 PDF下载
- VTK能干什么?VTK大部分功能的细节简介,VTK能打开的文件格式
- 在CSDN写博客五年之后,我成为了博客专家
- VTK - 冠脉重建点匹配坐标数据下载
- 资源分享 - OpenGL编程指南(原书第8版)- OpenGL红宝书高清带书签PDF下载
- 简单粗暴:使用pycharm安装对应的Python版本第三方包
- Pip - 常用命令(安装,卸载,升级第三方库)
- 资源分享 - Fluid Simulation for Computer Graphics, First Edition英文高清PDF下载
- C++ 11 - final关键字简要介绍
- C++11 - 基于无锁队列的单生产者单消费者模型