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