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;
}
相关推荐
序属秋秋秋1 小时前
《C++初阶之内存管理》【内存分布 + operator new/delete + 定位new】
开发语言·c++·笔记·学习
ruan1145142 小时前
MySQL4种隔离级别
java·开发语言·mysql
quant_19863 小时前
R语言如何接入实时行情接口
开发语言·经验分享·笔记·python·websocket·金融·r语言
百锦再7 小时前
详细解析 .NET 依赖注入的三种生命周期模式
java·开发语言·.net·di·注入·模式·依赖
风吹落叶花飘荡7 小时前
2025 Next.js项目提前编译并在服务器
服务器·开发语言·javascript
失败又激情的man8 小时前
python之requests库解析
开发语言·爬虫·python
专注VB编程开发20年8 小时前
常见 HTTP 方法的成功状态码200,204,202,201
开发语言·网络协议·tcp/ip·http
有没有没有重复的名字8 小时前
线程安全的单例模式与读者写者问题
java·开发语言·单例模式
十秒耿直拆包选手8 小时前
Qt:主窗体(QMainwindow)初始化注意事项
c++·qt
开开心心_Every9 小时前
便捷的电脑自动关机辅助工具
开发语言·人工智能·pdf·c#·电脑·音视频·sublime text