C++学习系列(12):C++ 线程与多线程编程

C++学习系列(12):C++ 线程与多线程编程

1. 引言

在现代计算中,多线程(Multithreading) 通过 并发执行任务 来提高程序性能。C++11 引入了 标准线程库,大大简化了多线程编程。

本篇博客将介绍:

  • C++11 线程库
  • std::thread 的基本用法
  • 线程同步(mutex、lock、condition_variable)
  • std::asyncstd::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_guardunique_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),敬请期待!🚀

💡 如果你喜欢这篇文章,欢迎点赞、收藏,并关注本系列!

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值