在 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;
}
包含头文件:
#include <thread>
:提供线程支持。#include <vector>
:用于存储线程对象。#include <iostream>
:用于输入输出操作。线程函数:
void helloFunction(int id)
是一个简单的函数,它接受一个整数参数并打印一条消息。创建线程:
std::thread
创建线程对象,并将线程函数和参数传递给它。threads.emplace_back(helloFunction, i);
创建一个新线程并立即开始执行 helloFunction(i)
。等待线程完成:
join()
方法等待每个线程完成。如果不调用 join()
,主线程可能会在子线程完成之前退出,导致未定义行为。编译和运行:
g++ -std=c++11 -pthread your_program.cpp -o your_program
./your_program
std::mutex
)或其他同步机制来保护共享数据。通过以上步骤,你可以在 Linux 下使用 C++ 实现多线程编程。