往期回顾:
C++ 入门第24天:C++11 多线程基础
前言
多线程是现代计算机程序的重要组成部分,它允许我们同时执行多个任务,从而提高程序的性能。C++11 引入了标准线程库,使多线程编程更加方便和高效。
今天,我们将学习 C++ 多线程的基础,包括如何创建和管理线程,以及线程同步的基本知识。
1. 什么是多线程?
多线程是一种允许程序同时运行多个独立任务的技术。每个任务称为一个线程,它们共享相同的进程资源,但独立执行代码。
常见多线程的应用场景:
- 数据处理(如文件读取和写入)
- 用户界面(UI)响应
- 并行计算
2. 创建线程
C++11 提供了 std::thread 类来创建和管理线程。我们可以通过以下三种方式创建线程:
2.1 使用普通函数
#include <iostream>
#include <thread>
using namespace std;
void print_message() {
cout << "Hello from thread!" << endl;
}
int main() {
// 创建线程并运行
thread t(print_message);
// 等待线程完成
t.join();
return 0;
}
输出结果:
Hello from thread!
解释:
thread t(print_message);:创建线程并执行print_message函数。t.join();:主线程等待子线程完成后再继续执行。
2.2 使用 Lambda 表达式
#include <iostream>
#include <thread>
using namespace std;
int main() {
// 使用 Lambda 表达式创建线程
thread t([]() {
cout << "Hello from Lambda thread!" << endl;
});
t.join();
return 0;
}
输出结果:
Hello from Lambda thread!
2.3 使用类成员函数
#include <iostream>
#include <thread>
using namespace std;
class Worker {
public:
void operator()() {
cout << "Hello from Worker thread!" << endl;
}
};
int main() {
// 使用类的对象创建线程
Worker worker;
thread t(worker);
t.join();
return 0;
}
输出结果:
Hello from Worker thread!
3. 线程同步
多线程程序中,多个线程可能同时访问共享资源,这可能导致数据竞争和结果错误。C++ 提供了多种工具来解决这些问题。
3.1 使用 std::mutex
std::mutex 是一种互斥锁,用于确保同一时刻只有一个线程可以访问共享资源。
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
mutex mtx;
void print_numbers(int id) {
for (int i = 0; i < 5; i++) {
// 加锁
mtx.lock();
cout << "Thread " << id << ": " << i << endl;
// 解锁
mtx.unlock();
}
}
int main() {
thread t1(print_numbers, 1);
thread t2(print_numbers, 2);
t1.join();
t2.join();
return 0;
}
输出结果(顺序可能不同):
Thread 1: 0 Thread 1: 1 Thread 2: 0 Thread 2: 1 ...
3.2 使用 std::lock_guard
std::lock_guard 是一种更安全的方式,它会在作用域结束时自动释放锁。
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
mutex mtx;
void print_safe(int id) {
for (int i = 0; i < 5; i++) {
lock_guard<mutex> lock(mtx); // 自动加锁和解锁
cout << "Thread " << id << ": " << i << endl;
}
}
int main() {
thread t1(print_safe, 1);
thread t2(print_safe, 2);
t1.join();
t2.join();
return 0;
}
输出结果(线程安全):
Thread 1: 0 Thread 1: 1 Thread 2: 0 Thread 2: 1 ...
4. 线程间通信
线程之间可以通过共享变量或条件变量进行通信。
4.1 使用条件变量
条件变量允许一个线程等待另一个线程发出信号。
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
mutex mtx;
condition_variable cv;
bool ready = false;
void worker() {
unique_lock<mutex> lock(mtx);
cv.wait(lock, [] { return ready; }); // 等待 ready 为 true
cout << "Worker thread is processing!" << endl;
}
void signal() {
{
lock_guard<mutex> lock(mtx);
ready = true;
}
cv.notify_one(); // 通知等待的线程
}
int main() {
thread t1(worker);
thread t2(signal);
t1.join();
t2.join();
return 0;
}
输出结果:
Worker thread is processing!
结语
以上就是 C++ 11 多线程中的线程的创建、同步与线程间通信的基础知识点了。线程的创建使用普通函数、Lambda 表达式或类对象。线程同步通过 std::mutex 和 std::lock_guard 实现线程安全。线程间通信:通过条件变量实现线程之间的协调。多线程是 C++ 开发中的重要工具,可以显著提升程序性能。但同时,多线程编程也存在一定的复杂性,需小心处理数据竞争和死锁等问题。
都看到这里了,点个赞再走呗朋友~
加油吧,预祝大家变得更强!

被折叠的 条评论
为什么被折叠?



