阅读量:3
在 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_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 的 库,可以将代码修改为以下形式:
#include
#include
#include
// 线程函数
void thread_function(int thread_id) {
std::cout << "线程 " << thread_id << " 正在运行。" << std::endl;
}
int main() {
const int num_threads = 5;
std::vector 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;
}
编译和运行方法与之前的示例相同。
以上就是关于“如何用C++在Linux实现多线程”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm