linux

如何在Linux用C++实现多线程

小樊
52
2025-03-27 03:09:09
栏目: 编程语言

在 Linux 上使用 C++ 实现多线程主要依赖于 C++11 标准库中的 <thread> 头文件。以下是一个简单的示例,展示了如何创建和管理多个线程。

示例代码

#include <iostream>
#include <thread>
#include <vector>

// 线程函数
void helloThread(int threadId) {
    std::cout << "Hello from thread " << threadId << std::endl;
}

int main() {
    const int numThreads = 5;
    std::vector<std::thread> threads;

    // 创建线程
    for (int i = 0; i < numThreads; ++i) {
        threads.emplace_back(helloThread, i);
    }

    // 等待所有线程完成
    for (auto& th : threads) {
        if (th.joinable()) {
            th.join();
        }
    }

    std::cout << "All threads have finished." << std::endl;
    return 0;
}

代码说明

  1. 包含头文件

    • #include <iostream>:用于输入输出操作。
    • #include <thread>:提供多线程支持。
    • #include <vector>:用于存储线程对象。
  2. 线程函数

    • void helloThread(int threadId):这是一个简单的线程函数,接受一个整数参数 threadId,并打印一条消息。
  3. 主函数

    • const int numThreads = 5;:定义要创建的线程数量。
    • std::vector<std::thread> threads;:创建一个存储线程对象的向量。
    • 使用 for 循环创建线程,并将它们添加到向量中。threads.emplace_back(helloThread, i); 创建一个新线程,并调用 helloThread 函数,传递当前线程的 ID。
    • 使用另一个 for 循环等待所有线程完成。th.join(); 调用 join 方法等待线程结束。
  4. 编译和运行

    • 使用 g++ 编译器编译代码:
      g++ -std=c++11 -pthread your_program.cpp -o your_program
      
    • 运行生成的可执行文件:
      ./your_program
      

注意事项

通过以上步骤,你可以在 Linux 上使用 C++ 实现多线程编程。

0
看了该问题的人还看了