在 Windows 上使用 C++ 进行多线程编程通常涉及 Windows API 或标准线程库(C++11 及更高版本引入的 <thread>)。以下是如何使用这两种方法创建和管理线程的简要介绍。
使用 Windows API 进行多线程编程
Windows API 提供了一系列函数来创建和管理线程,如 CreateThread。以下是一个简单的例子:
#include <windows.h>
#include <iostream>
// 线程函数
DWORD WINAPI ThreadFunction(LPVOID lpParam) {
int threadNumber = *(reinterpret_cast<int*>(lpParam));
std::cout << "Thread " << threadNumber << " is running." << std::endl;
Sleep(2000); // 模拟一些工作
std::cout << "Thread " << threadNumber << " is exiting." << std::endl;
return 0;
}
int main() {
const int numThreads = 5;
HANDLE threads[numThreads];
int threadParams[numThreads];
// 创建线程
for (int i = 0; i < numThreads; ++i) {
threadParams[i] = i + 1;
threads[i] = CreateThread(
nullptr, // 默认安全属性
0, // 默认堆栈大小
ThreadFuncti