在 Linux 下使用 C++ 实现多线程,主要依赖于 <pthread.h> 库。以下是一个简单的示例,展示了如何创建和管理线程:
首先,确保你的编译器支持 C++11 或更高版本,因为 <thread> 库是在 C++11 中引入的。如果你使用的是较旧的编译器,可以使用 -pthread 标志来启用 pthread 支持。
创建一个名为 multithreading_example.cpp 的文件,并添加以下代码:
#include <iostream>
#include <pthread.h>
// 线程函数
void* thread_function(void* arg) {
int thread_id = *(static_cast<int*>(arg));
std::cout << "线程 " << thread_id << " 正在运行。" << std::endl;
return nullptr;
}
int main() {
const int num_threads = 5;
pthread_t threads[num_threads];
int thread_ids[num_threads];
// 创建线程
for (int i = 0; i < num_threads; ++i) {
thread_ids[i] = i;
if (pthread_create(&threads[i], nullptr, thread_function, &thread_ids[i]) != 0) {
std::cerr << "创建线程失败" << std::endl;
return 1;
}
}
// 等待线程结束
for (int i = 0; i < num_threads; ++i) {
pthread_join(threads[i], nullptr);
}
std::cout << "所有线程已完成。" << std::endl;
return 0;
}
g++ -pthread multithreading_example.cpp -o multithreading_example
./multithreading_example
这个示例创建了 5 个线程,每个线程都会打印其线程 ID。注意,线程的执行顺序可能会有所不同,因为它们是并发运行的。
如果你想使用 C++11 的 <thread> 库,可以将代码修改为以下形式:
#include <iostream>
#include <thread>
#include <vector>
// 线程函数
void thread_function(int thread_id) {
std::cout << "线程 " << thread_id << " 正在运行。" << std::endl;
}
int main() {
const int num_threads = 5;
std::vector<std::thread> threads;
// 创建线程
for (int i = 0; i < num_threads; ++i) {
threads.push_back(std::thread(thread_function, i));
}
// 等待线程结束
for (auto& t : threads) {
t.join();
}
std::cout << "所有线程已完成。" << std::endl;
return 0;
}
编译和运行方法与之前的示例相同。