C++之多线程(multi-thread)

理论基础

多线程编程是C++中一个重要而复杂的主题。下面是一些建议和步骤,帮助你入门多线程编程:

  1. 了解基础概念:

    线程和进程: 理解线程和进程的基本概念。

    并发和并行: 区分并发和并行的概念,了解它们在多线程编程中的应用。

  2. 学习C++11及以后的线程支持:

    C++11 引入了对多线程编程的支持,包括 std::thread 类等。

    学习如何创建、加入和分离线程。

cpp 复制代码
#include <iostream>
#include <thread>

void myFunction() {
    // 线程执行的函数
    std::cout << "Hello from thread!" << std::endl;
}

int main() {
    // 创建线程并执行函数
    std::thread myThread(myFunction);

    // 等待线程结束
    myThread.join();

    return 0;
}
  1. 理解线程同步和互斥:

    互斥锁(Mutex): 学习如何使用 std::mutex 来保护共享资源,防止多个线程同时访问。

    条件变量(Condition Variable): 了解如何使用 std::condition_variable 实现线程间的协同。

cpp 复制代码
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

std::mutex mtx;
std::condition_variable cv;
bool ready = false;

void worker() {
    std::unique_lock<std::mutex> lock(mtx);
    cv.wait(lock, []{ return ready; });

    // 线程执行的任务

    std::cout << "Worker thread is done." << std::endl;
}

int main() {
    std::thread myThread(worker);

    // 准备工作完成后通知线程
    {
        std::lock_guard<std::mutex> lock(mtx);
        ready = true;
    }
    cv.notify_one();

    myThread.join();

    return 0;
}
  1. 学习原子操作:

    原子操作: 了解如何使用 std::atomic 类型来进行原子操作,避免数据竞争。

cpp 复制代码
#include <iostream>
#include <thread>
#include <atomic>

std::atomic<int> counter(0);

void increment() {
    for (int i = 0; i < 1000000; ++i) {
        counter++;
    }
}

int main() {
    std::thread t1(increment);
    std::thread t2(increment);

    t1.join();
    t2.join();

    std::cout << "Counter value: " << counter << std::endl;

    return 0;
}
  1. 阅读相关书籍和资料:

    《C++ Concurrency in Action》(作者:Anthony Williams):深入讲解C++中的并发编程。
    C++ Multithreading:一个较为详细的在线教程。

  2. 实践多线程编程:

    尝试编写简单的多线程程序,理解线程之间的交互和共享资源的问题。

    解决一些典型的多线程问题,例如生产者-消费者问题等。

  3. 进一步学习:

    了解更高级的主题,如并行算法、任务调度等。

    探索C++标准库中与并发相关的其他组件,如 std::async、std::future 等。

最后的测试实例

cpp 复制代码
#include <iostream>
#include <vector>
#include <thread>
#include <mutex>
#include <chrono>
using namespace std;
std::mutex mtx;  // 互斥锁,用于保护共享资源
int sum = 0;     // 共享资源,存储数组的和

// 计算数组的和的函数
void calculateSum(const std::vector<int>& numbers, int start, int end) {
    int localSum = 0;

    for (int i = start; i < end; ++i) {
        localSum += numbers[i];
        cout << "numbers =" << numbers[i] << endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(10));

    }

    // 使用互斥锁保护对共享资源的访问
    std::lock_guard<std::mutex> lock(mtx);
    sum += localSum;
    cout << "sum =" << sum << endl;
}

int main() {
    // 创建一个包含整数的数组
    std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    // 定义线程的数量
    const int numThreads = 2;

    // 计算每个线程的工作量
    const int chunkSize = numbers.size() / numThreads;
    
    // 创建线程数组
    std::vector<std::thread> threads;

    // 启动线程
    for (int i = 0; i < numThreads; ++i) {
        int start = i * chunkSize;
        int end = (i == numThreads - 1) ? numbers.size() : (i + 1) * chunkSize;
        threads.emplace_back(calculateSum, std::ref(numbers), start, end);
        cout << "num threads" << i << endl;
    }

    // 等待所有线程完成
    for (auto& thread : threads) {
        thread.join();
    }

    // 输出最终的结果
    std::cout << "Sum of the array: " << sum << std::endl;

    return 0;
}
相关推荐
weixin_462446236 分钟前
使用 Go 实现 SSE 流式推送 + 打字机效果(模拟 Coze Chat)
开发语言·后端·golang
JIngJaneIL24 分钟前
基于springboot + vue古城景区管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
敲敲了个代码31 分钟前
隐式类型转换:哈基米 == 猫 ? true :false
开发语言·前端·javascript·学习·面试·web
asiwxy37 分钟前
OpenGL 材质
c++
小信啊啊1 小时前
Go语言切片slice
开发语言·后端·golang
阿华hhh1 小时前
Linux系统编程(标准io)
linux·开发语言·c++
南_山无梅落1 小时前
9.Python3集合(set)增删改查和推导式
java·开发语言
sg_knight1 小时前
拥抱未来:ECMAScript Modules (ESM) 深度解析
开发语言·前端·javascript·vue·ecmascript·web·esm
程序喵大人2 小时前
推荐个 C++ 练习平台
开发语言·c++·工具推荐
阿里嘎多学长2 小时前
2025-12-16 GitHub 热点项目精选
开发语言·程序员·github·代码托管