阅读量:3
在Linux中,C++多线程可以通过两种方式实现:使用POSIX线程库(pthread)或C++11标准库中的线程支持。
使用POSIX线程库(pthread)
POSIX线程库是Linux系统上广泛使用的多线程库。要使用它,你需要在编译时链接pthread库。
示例代码:
#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() {
pthread_t threads[5];
int thread_ids[5] = {0, 1, 2, 3, 4};
for (int i = 0; i < 5; ++i) {
if (pthread_create(&threads[i], nullptr, thread_function, &thread_ids[i]) != 0) {
std::cerr << "Error creating thread "<< i << std::endl;
return 1;
}
}
for (int i = 0; i < 5; ++i) {
pthread_join(threads[i], nullptr);
}
std::cout << "All threads have finished." << std::endl;
return 0;
}
编译命令:
g++ -o multi_thread_example multi_thread_example.cpp -pthread
使用C++11标准库中的线程支持
C++11引入了标准库中的线程支持,使得在C++中实现多线程变得更加简单和一致。
示例代码:
#include
#include
#include
void thread_function(int thread_id) {
std::cout << "Thread " << thread_id << " is running." << std::endl;
}
int main() {
std::vector threads;
for (int i = 0; i < 5; ++i) {
threads.emplace_back(thread_function, i);
}
for (auto& t : threads) {
t.join();
}
std::cout << "All threads have finished." << std::endl;
return 0;
}
编译命令:
g++ -o multi_thread_example multi_thread_example.cpp -std=c++11
这两种方法都可以实现C++多线程编程。C++11标准库中的线程支持提供了更简洁的语法和更好的跨平台兼容性,因此推荐使用C++11标准库中的线程支持。
以上就是关于“Linux中C++多线程怎样实现”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm