阅读量:2
在Linux中,C++程序可以通过多种方式实现多线程。以下是两种常用的方法:
方法一:使用POSIX线程(pthreads)
POSIX线程(pthreads)是一种广泛使用的多线程库,适用于Unix-like系统,包括Linux。
示例代码:
#include
#include
// 线程函数
void* thread_function(void* arg) {
int thread_id = *(static_cast<int*>(arg));
std::cout << "Thread " << thread_id << " is running." << 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 << "Failed to create thread "<< i << std::endl;
return 1;
}
}
// 等待线程结束
for (int i = 0; i < num_threads; ++i) {
pthread_join(threads[i], nullptr);
}
std::cout << "All threads have finished." << std::endl;
return 0;
}
编译和运行:
g++ -pthread -o multithread_example multithread_example.cpp
./multithread_example
方法二:使用C++11标准库中的
C++11引入了标准库中的多线程支持,使用头文件可以更方便地实现多线程编程。
示例代码:
#include
#include
#include
// 线程函数
void thread_function(int thread_id) {
std::cout << "Thread " << thread_id << " is running." << std::endl;
}
int main() {
const int num_threads = 5;
std::vector threads;
// 创建线程
for (int i = 0; i < num_threads; ++i) {
threads.emplace_back(thread_function, i);
}
// 等待线程结束
for (auto& t : threads) {
t.join();
}
std::cout << "All threads have finished." << std::endl;
return 0;
}
编译和运行:
g++ -std=c++11 -pthread -o multithread_example multithread_example.cpp
./multithread_example
总结
- POSIX线程(pthreads):适用于需要跨平台兼容性的项目,但需要手动管理线程的生命周期。
- C++11标准库中的
:提供了更现代和简洁的多线程编程接口,推荐在C++11及以上版本中使用。
选择哪种方法取决于你的具体需求和项目环境。
以上就是关于“Linux中C++程序如何实现多线程”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm