在 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;
}
包含头文件:
#include <iostream>:用于输入输出操作。#include <thread>:提供多线程支持。#include <vector>:用于存储线程对象。线程函数:
void helloThread(int threadId):这是一个简单的线程函数,接受一个整数参数 threadId,并打印一条消息。主函数:
const int numThreads = 5;:定义要创建的线程数量。std::vector<std::thread> threads;:创建一个存储线程对象的向量。for 循环创建线程,并将它们添加到向量中。threads.emplace_back(helloThread, i); 创建一个新线程,并调用 helloThread 函数,传递当前线程的 ID。for 循环等待所有线程完成。th.join(); 调用 join 方法等待线程结束。编译和运行:
g++ 编译器编译代码:g++ -std=c++11 -pthread your_program.cpp -o your_program
./your_program
std::mutex)、条件变量(std::condition_variable)等同步机制。join 或 detach 方法,以避免资源泄漏。通过以上步骤,你可以在 Linux 上使用 C++ 实现多线程编程。