C++:Windows 多线程 简单示例

在 Windows 上使用 C++ 进行多线程编程通常涉及 Windows API 或标准线程库(C++11 及更高版本引入的 <thread>)。以下是如何使用这两种方法创建和管理线程的简要介绍。

使用 Windows API 进行多线程编程

Windows API 提供了一系列函数来创建和管理线程,如 CreateThread。以下是一个简单的例子:

cpp 复制代码
#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,             // 默认堆栈大小
            ThreadFunction,// 线程函数
            &threadParams[i], // 传递给线程函数的参数
            0,             // 默认创建标志
            nullptr        // 不需要返回线程标识符
        );
 
        if (threads[i] == nullptr) {
            std::cerr << "Error creating thread " << i + 1 << std::endl;
            return 1;
        }
    }
 
    // 等待所有线程完成
    WaitForMultipleObjects(numThreads, threads, TRUE, INFINITE);
 
    // 关闭线程句柄
    for (int i = 0; i < numThreads; ++i) {
        CloseHandle(threads[i]);
    }
 
    return 0;
}

使用 C++11 标准库进行多线程编程

C++11 引入了 <thread> 库,使得多线程编程变得更加直观和跨平台。以下是一个使用 <thread> 的简单例子:

cpp 复制代码
#include <iostream>
#include <thread>
#include <vector>
 
// 线程函数
void threadFunction(int threadNumber) {
    std::cout << "Thread " << threadNumber << " is running." << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(2)); // 模拟一些工作
    std::cout << "Thread " << threadNumber << " is exiting." << std::endl;
}
 
int main() {
    const int numThreads = 5;
    std::vector<std::thread> threads;
 
    // 创建线程
    for (int i = 0; i < numThreads; ++i) {
        threads.emplace_back(threadFunction, i + 1);
    }
 
    // 等待所有线程完成
    for (auto& thread : threads) {
        thread.join();
    }
 
    return 0;
}

选择哪种方法?

Windows API:提供了更多的控制和底层访问,但代码通常更加复杂且特定于平台。

C++11 <thread>:更加简洁和跨平台,适合大多数应用场景。

对于大多数现代 C++ 项目,推荐使用 C++11 或更高版本的 <thread> 库,除非你有特定的需求需要使用 Windows API 的功能。

相关推荐
刘卜卜&嵌入式36 分钟前
C++_设计模式_观察者模式(Observer Pattern)
c++·观察者模式·设计模式
h汉堡1 小时前
C++入门基础
开发语言·c++·学习
XINVRY-FPGA1 小时前
XCZU7EG‑L1FFVC1156I 赛灵思XilinxFPGA ZynqUltraScale+ MPSoC EG
c++·嵌入式硬件·阿里云·fpga开发·云计算·fpga·pcb工艺
_GR2 小时前
2025年蓝桥杯第十六届C&C++大学B组真题及代码
c语言·数据结构·c++·算法·贪心算法·蓝桥杯·动态规划
mahuifa3 小时前
(7)VTK C++开发示例 --- 使用交互器
c++·vtk·cmake·3d开发
光算科技4 小时前
服务器在国外国内用户访问慢会影响谷歌排名吗?
运维·服务器·c++
大炮筒4 小时前
CPPlist初识
数据结构·c++·list
点云SLAM5 小时前
C++中的算术转换、其他隐式类型转换和显示转换详解
c++·static_cast·dynamic_cast·c++中的类型转换·算术类型转换·其他隐式类型转换·显示类型转换
Zfox_6 小时前
Git 进阶之路:高效协作之分支管理
大数据·linux·运维·c++·git·elasticsearch
wenchm6 小时前
细说STM32单片机FreeRTOS任务管理API函数vTaskList()的使用方法
c语言·c++·stm32·单片机·嵌入式硬件