一、基于POSIX线程库(pthreads)
适用场景:Linux/Unix系统、需要底层线程控制或兼容旧代码。
核心步骤:
- 包含头文件:
#include <pthread.h> - 定义线程函数:返回类型为
void*,参数为void*指针。 - 创建线程:使用
pthread_create函数。 - 等待线程结束:使用
pthread_join回收资源。
示例代码:
1#include <iostream> 2#include <pthread.h> 3 4void* threadFunction(void* arg) { 5 int id = *((int*)arg); 6 std::cout << "Thread " << id << " is running.\n"; 7 return nullptr; 8} 9 10int main() { 11 const int numThreads = 5; 12 pthread_t threads[numThreads]; 13 int threadIds[numThreads]; 14 15 for (int i = 0; i < numThreads; ++i) { 16 threadIds[i] = i; 17 if (pthread_create(&threads[i], nullptr, threadFunction, &threadIds[i]) != 0) { 18 std::cerr << "Failed to create thread "<< i << "\n"; 19 return 1; 20 } 21 } 22 23 for (int i = 0; i < numThreads; ++i) { 24 pthread_join(threads[i], nullptr); 25 } 26 27 std::cout << "All threads finished.\n"; 28 return 0; 29}
编译命令:
g++ -pthread -o multithread_example multithread_example.cpp
二、基于C++11标准库(<thread>)
适用场景:现代C++项目(C++11及以上)、跨平台开发。
核心优势:语法简洁,类型安全,支持RAII管理。
核心步骤:
- 包含头文件:
#include <thread> - 创建线程:直接实例化
std::thread对象,传入可调用对象(函数、Lambda等)。 - 管理线程:使用
join()等待线程结束或detach()分离线程。
示例代码:
1#include <iostream> 2#include <thread> 3#include <vector> 4 5void threadFunction(int id) { 6 std::cout << "Thread " << id << " is running.\n"; 7} 8 9int main() { 10 std::vector<std::thread> threads; 11 for (int i = 0; i < 5; ++i) { 12 threads.emplace_back(threadFunction, i); 13 } 14 15 for (auto& t : threads) { 16 if (t.joinable()) t.join(); 17 } 18 19 std::cout << "All threads finished.\n"; 20 return 0; 21}
编译命令:
g++ -std=c++11 -o multithread_example multithread_example.cpp
三、线程同步机制
多线程访问共享资源时需避免竞态条件,常用工具包括:
- 互斥锁(
std::mutex):
1#include <mutex> 2std::mutex mtx; 3void safePrint(int id) { 4 std::lock_guard<std::mutex> lock(mtx); // 自动加锁/解锁 5 std::cout << "Thread " << id << " is accessing shared data.\n"; 6}
- 条件变量(
std::condition_variable):
用于线程间通信,例如生产者-消费者模型:
1#include <condition_variable> 2std::condition_variable cv; 3bool ready = false; 4void worker() { 5 std::unique_lock<std::mutex> lock(mtx); 6 cv.wait(lock, []{ return ready; }); // 等待通知 7 // 执行任务 8} 9void trigger() { 10 { 11 std::lock_guard<std::mutex> lock(mtx); 12 ready = true; 13 } 14 cv.notify_all(); // 通知所有等待线程 15}
四、高级并发工具
std::async与std::future:
异步执行任务并获取返回值,适合简化并行任务管理:
1#include <future> 2int computeSum(int a, int b) { 3 return a + b; 4} 5int main() { 6 std::future<int> result = std::async(std::launch::async, computeSum, 3, 4); 7 std::cout << "Sum: " << result.get() << "\n"; // 阻塞等待结果 8 return 0; 9}
- 线程池(第三方库):
如Boost.Thread或自定义实现,用于复用线程减少创建/销毁开销。
五、方法对比与选择建议
| 方法 | 优点 | 缺点 | 适用场景 |
|---|---|---|---|
| pthreads | 底层控制灵活,兼容性强 | 语法繁琐,需手动管理资源 | 跨平台旧项目、精细控制需求 |
| C++11 <thread> | 语法简洁,RAII自动管理 | 依赖C++11及以上标准 | 现代C++项目、跨平台开发 |
| std::async | 简化异步任务管理,自动线程调度 | 任务调度策略由实现决定 | 需要返回值的并行任务 |
六、注意事项
- 线程安全:共享数据必须通过互斥锁、原子操作(
std::atomic)等保护。 - 资源泄漏:确保每个
pthread_create对应pthread_join,或使用detach()。 - 编译选项:
- pthread需添加
-pthread(Linux/CentOS)或-lpthread。 - C++11需添加
-std=c++11或更高版本标志。
- pthread需添加
《C++中实现多线程编程》 是转载文章,点击查看原文。

