linux

Linux C++如何实现多线程

小樊
47
2025-05-16 09:58:36
栏目: 编程语言

在 Linux 下使用 C++ 实现多线程,通常可以使用 C++11 标准库提供的 <thread> 头文件。以下是一个简单的示例,展示如何创建和管理多个线程:

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

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

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

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

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

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

代码说明:

  1. 包含头文件

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

    • void helloFunction(int id) 是一个简单的函数,它接受一个整数参数并打印一条消息。
  3. 创建线程

    • 使用 std::thread 创建线程对象,并将线程函数和参数传递给它。
    • threads.emplace_back(helloFunction, i); 创建一个新线程并立即开始执行 helloFunction(i)
  4. 等待线程完成

    • 使用 join() 方法等待每个线程完成。如果不调用 join(),主线程可能会在子线程完成之前退出,导致未定义行为。
  5. 编译和运行

    • 使用支持 C++11 或更高版本的编译器进行编译,例如:
      g++ -std=c++11 -pthread your_program.cpp -o your_program
      
    • 运行生成的可执行文件:
      ./your_program
      

注意事项:

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

0
看了该问题的人还看了