C++学习系列(12):C++ 线程与多线程编程
1. 引言
在现代计算中,多线程(Multithreading) 通过 并发执行任务 来提高程序性能。C++11 引入了 标准线程库,大大简化了多线程编程。
本篇博客将介绍:
- C++11 线程库
std::thread的基本用法- 线程同步(mutex、lock、condition_variable)
std::async与std::future
2. std::thread 基础
2.1 创建线程
C++11 使用 std::thread 来创建线程:
#include <iostream>
#include <thread>
void hello() {
std::cout << "Hello, Thread!\n";
}
int main() {
std::thread t(hello); // 创建线程
t.join(); // 等待线程执行完毕
return 0;
}
📌 解析
std::thread t(hello);✅ 创建线程t.join();✅ 等待线程结束
2.2 线程的 join() 和 detach()
std::thread t(hello);
t.join(); // ✅ 等待线程执行完毕
t.detach(); // ✅ 让线程在后台运行
📌 注意
join():阻塞主线程,直到子线程结束。detach():让子线程在后台运行,主线程不再管理。
3. 线程同步(Mutex)
多线程访问共享资源时可能会发生 数据竞争(Race Condition),使用 std::mutex 互斥量 保护数据。
3.1 std::mutex 互斥锁
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
void print_message(const std::string &msg) {
std::lock_guard<std::mutex> lock(mtx); // 自动加锁 & 解锁
std::cout << msg << std::endl;
}
int main() {
std::thread t1(print_message, "Hello from Thread 1");
std::thread t2(print_message, "Hello from Thread 2");
t1.join();
t2.join();
return 0;
}
📌 解析
std::mutex mtx;✅ 定义互斥锁std::lock_guard<std::mutex> lock(mtx);✅ 自动加锁 & 解锁
3.2 std::unique_lock
std::unique_lock<std::mutex> lock(mtx);
✅ 相比 lock_guard,unique_lock 更灵活,支持 lock()/unlock()。
4. 线程间通信(Condition Variable)
std::condition_variable 用于线程间的等待与通知。
4.1 生产者-消费者模型
#include <iostream>
#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>
std::queue<int> dataQueue;
std::mutex mtx;
std::condition_variable cv;
void producer() {
for (int i = 0; i < 5; ++i) {
std::unique_lock<std::mutex> lock(mtx);
dataQueue.push(i);
std::cout << "Produced: " << i << std::endl;
cv.notify_one();
}
}
void consumer() {
while (true) {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [] { return !dataQueue.empty(); });
int value = dataQueue.front();
dataQueue.pop();
std::cout << "Consumed: " << value << std::endl;
}
}
int main() {
std::thread t1(producer);
std::thread t2(consumer);
t1.join();
t2.detach(); // 让消费者线程在后台运行
return 0;
}
📌 解析
std::condition_variable cv;✅ 条件变量cv.wait(lock, [] { return !dataQueue.empty(); });✅ 等待数据cv.notify_one();✅ 唤醒消费者
5. std::async & std::future
C++11 提供了 std::async 进行异步任务,返回值可用 std::future 获取。
5.1 std::async 示例
#include <iostream>
#include <future>
int compute(int x) {
return x * x;
}
int main() {
std::future<int> result = std::async(compute, 10);
std::cout << "计算结果: " << result.get() << std::endl;
return 0;
}
📌 解析
std::future<int> result = std::async(compute, 10);✅ 创建异步任务result.get();✅ 获取返回值
6. 总结
✅ std::thread 创建线程
✅ std::mutex 保护共享资源
✅ std::condition_variable 线程间通信
✅ std::async 执行异步任务
📢 下一篇 C++学习系列(13):C++ 并行算法(Parallel Algorithms),敬请期待!🚀
💡 如果你喜欢这篇文章,欢迎点赞、收藏,并关注本系列!

被折叠的 条评论
为什么被折叠?



