C++编程之多线程与并发

一、简介

多线程与并发编程是现代软件开发的重要组成部分。C++11 引入了一套全新的 线程库并发工具,极大地简化了多线程编程。

多线程的主要优点:

  • 提高程序的执行效率,充分利用多核处理器。
  • 实现任务的并发执行,提高响应速度。

二、C++11 标准中的线程库

1、线程的概念

线程(Thread) 是程序执行的基本单位,一个程序可以包含多个线程,每个线程执行不同的任务。

2、C++11 的线程库

C++11 提供了 std::thread 类用于管理线程,还引入了 互斥锁条件变量原子操作 等同步工具,帮助开发者安全地管理多线程环境。


三、线程的创建与同步

1、线程的创建

(1)基本用法

线程的创建使用 std::thread,可以通过函数指针、函数对象或 Lambda 表达式来指定线程任务。

代码示例:

#include <iostream>
#include <thread>
using namespace std;

void printMessage(const string &message) {
    for (int i = 0; i < 5; ++i) {
        cout << message << " (" << i + 1 << ")" << endl;
    }
}

int main() {
    thread t1(printMessage, "Hello from thread 1"); // 创建线程
    thread t2([]() { // 使用 Lambda 表达式
        for (int i = 0; i < 5; ++i) {
            cout << "Hello from thread 2 (" << i + 1 << ")" << endl;
        }
    });

    t1.join(); // 等待 t1 执行完毕
    t2.join(); // 等待 t2 执行完毕

    return 0;
}

运行结果(可能不同步):

Hello from thread 1 (1)
Hello from thread 2 (1)
...

2、线程的同步

在多线程环境中,多个线程可能会同时访问共享资源,导致数据竞争问题。C++11 提供了以下同步机制:

(1)互斥锁(Mutex)

概念: 互斥锁用于保护临界区,确保同一时间只有一个线程可以访问共享资源。

代码示例:

#include <iostream>
#include <thread>
#include <mutex>
using namespace std;

mutex mtx; // 创建互斥锁
int sharedCounter = 0;

void incrementCounter() {
    for (int i = 0; i < 10000; ++i) {
        lock_guard<mutex> lock(mtx); // 自动加锁与解锁
        ++sharedCounter;
    }
}

int main() {
    thread t1(incrementCounter);
    thread t2(incrementCounter);

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

    cout << "Final counter value: " << sharedCounter << endl;
    return 0;
}

运行结果:

Final counter value: 20000

(2)条件变量(Condition Variable)

概念: 条件变量用于线程间的等待与通知,常与互斥锁结合使用。

代码示例:

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;

mutex mtx;
condition_variable cv;
bool ready = false;

void printMessage() {
    unique_lock<mutex> lock(mtx);
    cv.wait(lock, [] { return ready; }); // 等待 ready 变为 true
    cout << "Thread is running!" << endl;
}

void setReady() {
    {
        lock_guard<mutex> lock(mtx);
        ready = true;
    }
    cv.notify_one(); // 通知等待的线程
}

int main() {
    thread t1(printMessage);
    thread t2(setReady);

    t1.join();
    t2.join();
    return 0;
}

运行结果:

Thread is running!

四、并发容器与原子操作

1、并发容器

C++ 标准库提供了一些线程安全的容器(如 std::queuestd::priority_queue)用于多线程环境。

2、原子操作

概念: std::atomic 提供了无锁的线程安全操作,适合于简单的计数和标志位。

代码示例:

#include <iostream>
#include <thread>
#include <atomic>
using namespace std;

atomic<int> counter(0);

void increment() {
    for (int i = 0; i < 10000; ++i) {
        ++counter; // 原子操作
    }
}

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

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

    cout << "Final counter value: " << counter << endl;
    return 0;
}

运行结果:

Final counter value: 20000

五、任务并行化与线程池

1、任务并行化

C++11 提供了 std::asyncstd::future 来实现任务并行化。

代码示例:

#include <iostream>
#include <future>
using namespace std;

int computeSum(int a, int b) {
    return a + b;
}

int main() {
    future<int> result = async(computeSum, 10, 20); // 异步执行
    cout << "Result: " << result.get() << endl; // 获取结果
    return 0;
}

运行结果:

Result: 30

2、线程池实现

线程池是一种高效的线程管理机制,多个任务共享有限的线程。

简单线程池实现:

#include <iostream>
#include <vector>
#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <functional>
using namespace std;

class ThreadPool {
private:
    vector<thread> workers;
    queue<function<void()>> tasks;
    mutex mtx;
    condition_variable cv;
    bool stop;

public:
    ThreadPool(size_t threads) : stop(false) {
        for (size_t i = 0; i < threads; ++i) {
            workers.emplace_back([this] {
                while (true) {
                    function<void()> task;
                    {
                        unique_lock<mutex> lock(mtx);
                        cv.wait(lock, [this] { return stop || !tasks.empty(); });
                        if (stop && tasks.empty()) return;
                        task = move(tasks.front());
                        tasks.pop();
                    }
                    task();
                }
            });
        }
    }

    void enqueue(function<void()> task) {
        {
            lock_guard<mutex> lock(mtx);
            tasks.emplace(task);
        }
        cv.notify_one();
    }

    ~ThreadPool() {
        {
            lock_guard<mutex> lock(mtx);
            stop = true;
        }
        cv.notify_all();
        for (thread &worker : workers) worker.join();
    }
};

int main() {
    ThreadPool pool(4);

    for (int i = 0; i < 8; ++i) {
        pool.enqueue([i] {
            cout << "Task " << i << " is running!" << endl;
        });
    }

    return 0;
}

运行结果(输出顺序可能不同):

Task 0 is running!
Task 1 is running!
...

六、小结

  1. 线程库: C++11 提供了 std::thread 和一系列同步工具。
  2. 同步机制: 包括互斥锁、条件变量和原子操作,保障线程安全。
  3. 任务并行化: 使用 std::async 实现任务异步执行。
  4. 线程池: 提高线程复用效率,适合大量小任务的并发执行。

通过学习多线程与并发,可以编写高效且健壮的多核并行程序。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

人间酒中仙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值