在 C++ 中,使用 Windows API 實(shí)現(xiàn)多線(xiàn)程可以通過(guò)以下步驟完成:
#include <Windows.h>
#include <iostream>
#include <vector>
#include <thread>
void worker_function(int thread_id) {
std::cout << "Hello from thread " << thread_id << std::endl;
}
main
函數(shù)中創(chuàng)建多個(gè)線(xiàn)程:int main() {
const int num_threads = 5;
// 創(chuàng)建一個(gè)線(xiàn)程向量
std::vector<std::thread> threads;
// 啟動(dòng)新線(xiàn)程并添加到向量中
for (int i = 0; i < num_threads; ++i) {
threads.emplace_back(worker_function, i);
}
// 等待所有線(xiàn)程完成
for (auto& thread : threads) {
if (thread.joinable()) {
thread.join();
}
}
return 0;
}
這個(gè)示例展示了如何使用 C++11 的 std::thread
類(lèi)來(lái)簡(jiǎn)化多線(xiàn)程操作。如果你只想使用 Windows API,可以參考以下代碼:
#include <Windows.h>
#include <iostream>
#include <vector>
DWORD WINAPI worker_function(LPVOID lpParam) {
int thread_id = reinterpret_cast<int>(lpParam);
std::cout << "Hello from thread " << thread_id << std::endl;
return 0;
}
main
函數(shù)中創(chuàng)建多個(gè)線(xiàn)程:int main() {
const int num_threads = 5;
// 創(chuàng)建一個(gè)線(xiàn)程向量
std::vector<HANDLE> threads;
// 啟動(dòng)新線(xiàn)程并添加到向量中
for (int i = 0; i < num_threads; ++i) {
HANDLE hThread = CreateThread(
nullptr, // 默認(rèn)安全屬性
0, // 默認(rèn)堆棧大小
worker_function, // 線(xiàn)程函數(shù)
reinterpret_cast<LPVOID>(i), // 傳遞給線(xiàn)程函數(shù)的參數(shù)
0, // 使用默認(rèn)創(chuàng)建標(biāo)志
nullptr // 不需要線(xiàn)程 ID
);
if (hThread == nullptr) {
std::cerr << "Error creating thread" << std::endl;
return 1;
}
threads.push_back(hThread);
}
// 等待所有線(xiàn)程完成
for (auto& hThread : threads) {
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
}
return 0;
}
這個(gè)示例展示了如何使用 Windows API 的 CreateThread
函數(shù)來(lái)創(chuàng)建新線(xiàn)程。注意,這里我們使用 std::vector<HANDLE>
來(lái)存儲(chǔ)線(xiàn)程句柄,以便稍后等待它們完成并關(guān)閉它們。