C++ 多线程基础
概述
线程(Thread)
- 线程是程序执行中的单一顺序控制流,多个线程可以在同一个进程中独立运行
- 线程共享进程的地址空间、文件描述符、堆和全局变量等资源,但每个线程有自己的栈、寄存器和程序计数器
并发(Concurrency)与并行(Parallelism)
- 并发:多个任务在时间片段内交替执行,表现出同时进行的效果。
- 并行:多个任务在多个处理器或处理器核上同时执行
C++11标准引入了原生的多线程支持,通过
std::thread:用于创建线程和管理线程std::mutex:用于线程之间的互斥,防止多个线程同时访问共享资源。std::lock_guard和std::unique_lock:用于管理锁的获取和释放。std::future和std::promise:用于实现线程间的值传递和任务同步
创建线程
通过std::thread来创建线程
std::thread thread_obj(callable, args...)
- callable: 可调用对象,可以是函数指针、函数对象、Lambda表达式等。
- args...: 传递给
callable的参数列表
使用函数指针
通过函数指针创建线程,这是最基本的方式:
#include <iostream>
#include <thread>// 基本线程函数
void thread_func(int id) {std::cout << "线程" << id << " 正在运行" << std::endl;
}int main() {// 创建线程std::thread t1(thread_func, 1); // 创建线程,传递函数指针和参数std::thread t2(thread_func, 2);t1.join(); // 等待线程完成t2.join(); // 等待线程完成return 0;
}
运行结果:

两个现场同时执行 导致控制台打印错乱
使用函数对象
通过类中的operator()方法定义函数对象来创建线程:
#include <iostream>
#include <thread>class PrintTask {
public:void operator()(int count) const {for (int i = 0; i < count; ++i) {std::cout << "Hello from thread (function object)!\n";}}
};int main() {std::thread t2(PrintTask(), 5); // 创建线程,传递函数对象和参数t2.join(); // 等待线程完成return 0;
}
使用Lambda表达式
Lambda表达式可以直接内联定义线程执行的代码:
#include <iostream>
#include <thread>
int main() {// 使用lambda表达式创建线程std::thread t3([](int num) {std::cout << "Lambda线程" << num << " 正在运行" << std::endl;}, 3); // 创建线程,传递 Lambda 表达式和参数t3.join();// 等待线程完成return 0;
}
线程管理
join()
join()用于等待线程完成执行。如果不调用join()或detach()而直接销毁线程对象,会导致程序崩溃。
t.join();
detach()
detach()将线程与主线程分离,线程在后台独立运行,主线程不再等待它。
t.detach();
线程的传参
值传递
参数可以通过值传递给线程:
std::thread t(func, arg1, arg2);
引用传递
如果需要传递引用参数, 需要使用std::ref:
#include <iostream>
#include <thread>void increment(int& x) {++x;
}int main() {int num = 0;std::thread t(increment, std::ref(num)); // 使用 std::ref 传递引用t.join();std::cout << "Value after increment: " << num << std::endl;return 0;
}