C++进阶之结合std::thread + lambda:用法实例(四百三十六)
·
简介: CSDN博客专家、《Android系统多媒体进阶实战》作者
博主新书推荐:《Android系统多媒体进阶实战》🚀
Android Audio工程师专栏地址: Audio工程师进阶系列【原创干货持续更新中……】🚀
Android多媒体专栏地址: 多媒体系统工程师系列【原创干货持续更新中……】🚀
专题一 二:AAOS车载系统+AOSP14系统攻城狮入门视频实战课 🚀
专题三:Android14 Binder之HIDL与AIDL通信实战课 🚀
专题四:Android15快速自定义与集成音效实战课 🚀
专题五:Android15音频策略实战课 🚀
专题六:Android15音频性能实战课(无声/杂音/断音/爆音实战案例) 🚀
人生格言: 人生从来没有捷径,只有行动才是治疗恐惧和懒惰的唯一良药.

🍉🍉🍉文章目录🍉🍉🍉
🌻1. 前言
本篇目的:C++ 进阶之结合 std::thread + lambda:用法实例
🌻2. C++ 结合 std::thread + lambda 介绍
- 基本概念
std::thread构造函数可以接收任何可调用对象(Callable)。Lambda 表达式作为匿名函数,可以直接内联定义在线程创建处,避免了定义额外全局函数的麻烦。 - 功能
支持捕获当前作用域变量(按值或引用)、直接传递参数给线程函数、实现闭包逻辑,从而简化多线程代码的结构。 - 使用限制
必须在std::thread对象析构前调用join()或detach();引用捕获时必须确保局部变量在子线程运行结束前不被销毁;std::thread对象本身不支持拷贝。 - 性能特性
Lambda 闭包类型由编译器在编译期确定,通常比std::bind具有更高的内联优化空间,运行时开销极低。 - 使用场景
临时异步任务、音视频流的分离处理、并发计算、UI 线程与耗时逻辑分离、类成员函数内部的异步回调。
🌻3. 代码实例
🌻3.1 基础演进:从普通函数到 Lambda
- 应用场景
对比传统函数指针(v1.0)与 Lambda(v2.0)的写法差异。 - 用法实例
#include <thread>
#include <mutex>
#include <condition_variable>
#include <iostream>
using namespace std;
// 创建线程执行函数
void thread_func(int id) {
std::cout << "Thread " << id << " running\n";
}
int main() {
// v1.0:使用普通函数指针创建线程
// std::thread t1(thread_func, 1);
// v2.0:结合 Lambda 表达式创建线程
// 使用 [&] 捕获外部变量,2 为传递给 Lambda 的参数
std::thread t2([&](int id) {
std::cout << "Lambda thread : id = " << id << "\n";
}, 2);
// t1.join(); // 等待线程结束
t2.join();
return 0;
}
输出:Lambda thread : id = 2
🌻3.2 Lambda 捕获外部局部变量引用
- 应用场景
在子线程中直接修改主线程的局部状态,无需通过参数传递。 - 用法实例
#include <iostream>
#include <thread>
int main() {
int count = 100;
// 通过 [&] 引用捕获外部 count 变量
std::thread t([&]() {
count += 50;
std::cout << "Child count: " << count << std::endl;
});
t.join();
std::cout << "Main count: " << count << std::endl;
}
输出:Child count: 150Main count: 150
🌻3.3 在类成员函数中使用 Lambda 创建线程
- 应用场景
Android/Linux 开发中,在类对象内部启动异步任务并访问类成员。 - 用法实例
#include <iostream>
#include <thread>
#include <string>
class AudioPlayer {
public:
void startAsync(const std::string& fileName) {
// 捕获 this 指针以访问成员函数,捕获 fileName 以获取路径
std::thread([this, fileName]() {
this->decode(fileName);
}).detach(); // 后台运行
}
private:
void decode(const std::string& file) {
std::cout << "Decoding: " << file << std::endl;
}
};
int main() {
AudioPlayer player;
player.startAsync("music.mp3");
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
输出:Decoding: music.mp3
🌻3.4 结合 Mutex 的并发控制
- 应用场景
多个 Lambda 线程安全地访问共享资源。 - 用法实例
#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
std::mutex mtx;
int main() {
std::vector<std::thread> pool;
for(int i = 0; i < 3; ++i) {
pool.emplace_back([i]() {
std::lock_guard<std::mutex> lock(mtx);
std::cout << "Task " << i << " executing..." << std::endl;
});
}
for(auto& t : pool) t.join();
}
🌻3.5 std::thread + lambda 总结
| 关键字 | 功能描述 | 典型应用 |
|---|---|---|
| std::thread | 创建并发执行流 | 异步处理、多核加速 |
| [&] / [=] | 变量捕获机制 | 上下文数据传递、闭包 |
| join / detach | 线程生命周期管理 | 资源同步、后台运行 |
| Callable | 任意可调用对象 | Lambda、函数指针、仿函数 |
更多推荐




所有评论(0)