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::queue
和 std::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::async
和 std::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!
...
六、小结
- 线程库: C++11 提供了
std::thread
和一系列同步工具。 - 同步机制: 包括互斥锁、条件变量和原子操作,保障线程安全。
- 任务并行化: 使用
std::async
实现任务异步执行。 - 线程池: 提高线程复用效率,适合大量小任务的并发执行。
通过学习多线程与并发,可以编写高效且健壮的多核并行程序。