目录
- [一、C++11 标准库 <thread> 实现多线程编程](#一、C++11 标准库 <thread> 实现多线程编程)
-
- [1. 基本线程创建](#1. 基本线程创建)
- [2. 线程管理](#2. 线程管理)
- [3. 线程传参](#3. 线程传参)
- [4. 同步机制](#4. 同步机制)
- [5. 异步编程](#5. 异步编程)
- [二、Windows API 实现多线程编程](#二、Windows API 实现多线程编程)
-
- [1. 基本线程创建](#1. 基本线程创建)
- [2. 线程管理](#2. 线程管理)
- [3. 线程传参](#3. 线程传参)
- 三、两种方法的对比
在 Windows 平台上使用 C++ 进行多线程编程,可以通过 C++11 标准库 或 Windows API 实现。以下是详细介绍:
一、C++11 标准库 实现多线程编程
1. 基本线程创建
- 函数指针:通过函数指针创建线程,是最基本的方式。
- Lambda 表达式:Lambda 表达式可以直接内联定义线程执行的代码。
- 类成员函数:通过类中的 operator() 方法定义函数对象来创建线程,或直接调用类的成员函数。
2. 线程管理
- join():等待线程完成执行。如果不调用 join() 或 detach() 而直接销毁线程对象,会导致程序崩溃。
- detach():将线程与主线程分离,线程在后台独立运行,主线程不再等待它。
3. 线程传参
- 值传递:参数可以通过值传递给线程。
- 引用传递:如果需要传递引用参数,需要使用 std::ref。
4. 同步机制
- 互斥量(std::mutex):用于保护共享数据,防止数据竞争。
- 锁(std::lock_guard 和 std::unique_lock):用于管理锁的获取和释放。
- 条件变量(std::condition_variable):用于线程间的条件变量,协调线程间的等待和通知。
5. 异步编程
std::async 和 std::future:用于实现线程间的值传递和任务同步,可以在不创建线程的情况下实现并发执行。
示例代码
cpp
#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
std::mutex mtx;
void printMessage(int id) {
std::lock_guard<std::mutex> lock(mtx);
std::cout << "Thread " << id << " is running.\n";
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Thread " << id << " has finished.\n";
}
int main() {
std::vector<std::thread> threads;
for (int i = 0; i < 5; ++i) {
threads.emplace_back(printMessage, i);
}
for (auto& thread : threads) {
thread.join();
}
std::cout << "All threads have completed.\n";
return 0;
}
二、Windows API 实现多线程编程
1. 基本线程创建
使用 CreateThread 函数创建线程,需要手动管理线程句柄和资源。
2. 线程管理
WaitForSingleObject 或 WaitForMultipleObjects:用于等待线程完成。
CloseHandle:用于关闭线程句柄,释放资源。
3. 线程传参
通过指针传递参数给线程函数。
示例代码
cpp
#include <iostream>
#include <windows.h>
DWORD WINAPI ThreadFunction(LPVOID lpParam) {
int id = *static_cast<int*>(lpParam);
std::cout << "Thread " << id << " is running.\n";
Sleep(1000); // Windows API 中的 Sleep 函数,单位为毫秒
std::cout << "Thread " << id << " has finished.\n";
return 0;
}
int main() {
HANDLE threads[5];
int threadIds[5] = {0, 1, 2, 3, 4};
for (int i = 0; i < 5; ++i) {
threads[i] = CreateThread(
NULL, // 默认安全属性
0, // 默认堆栈大小
ThreadFunction, // 线程函数
&threadIds[i], // 传递给线程函数的参数
0, // 默认创建标志
NULL // 线程ID(不返回)
);
}
WaitForMultipleObjects(5, threads, TRUE, INFINITE); // 等待所有线程完成
for (int i = 0; i < 5; ++i) {
CloseHandle(threads[i]); // 关闭线程句柄
}
std::cout << "All threads have completed.\n";
return 0;
}
三、两种方法的对比
C++11 :
优点:跨平台兼容性好,代码简洁,易于维护。
适用场景:需要跨平台支持的项目。
Windows API:
优点:提供更底层的控制,适合需要特定 Windows 功能的项目。
缺点:代码复杂,不跨平台。
适用场景:仅在 Windows 平台上运行的项目,且需要利用 Windows 特有的线程功能。