深入学习c++--多线程编程(一)
1. 简介
2. 线程使用
2.1 demo
#include <iostream> #include <thread> #include <future> using namespace std; void helloworld() { cout << "hello world \n"; } int main() { //开启一个线程 std::thread t(helloworld); std::cout << "hello world main thread\n"; //线程的终结 t.join(); return 0; }
2.2 一个简单的应用
- 查看当前线程id: this_thread::get_id()
- 比较单线程和多线程工作的效率(如果工作不太消耗时间,多线程反而比单线程更耗时间)
#include <iostream> #include <thread> #include <chrono> #include <future> #include <cmath> #include <vector> #include <cstdlib> using namespace std; double caculate(int v) { if (v <= 0) { return v; } //假设这个计算很慢 this_thread::sleep_for(chrono::milliseconds(10)); return sqrt((v * v + sqrt((v - 5) * (v + 2.5)) / 2.0) / v); } template<typename Iter, typename Fun> double visitRange(thread::id id, Iter iterBegin, Iter iterEnd, Fun func) { auto curId = this_thread::get_id(); if (id == this_thread::get_id()) { cout << curId << " hello main thread\n"; } else { cout << curId << " hello work thread\n"; } double v = 0; for (auto iter = iterBegin; iter != iterEnd; ++iter) { v += func(*iter); } return v; } int main() { auto mainThreadId = std::this_thread::get_id(); //开启一个线程 std::vector<double> v; for (int i = 0; i < 1000; i++) { v.push_back(rand()); } cout << v.size() << endl; double value = 0.0; auto st = clock(); for (auto & info : v) { value += caculate(info); } auto ed = clock(); cout << "single thread: " << value << " " << ed - st << "time" << endl; //下面用多线程来进行 auto iterMid = v.begin() + (v.size() / 2); // 指向整个vector一半部分 //计算后半部分 double anotherv = 0.0; auto iterEnd = v.end(); st = clock(); std::thread s([&anotherv, mainThreadId, iterMid, iterEnd]() { // lambda anotherv = visitRange(mainThreadId, iterMid, iterEnd, caculate); }); // 计算前半部分 auto halfv = visitRange(mainThreadId, v.begin(), iterMid, caculate); //关闭线程 s.join(); ed = clock(); cout << "multi thread: " << (halfv + anotherv) << " " << ed - st << "time" << endl; return 0; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理