在Linux下使用C++实现多线程,通常会使用POSIX线程库(pthread)。以下是一个简单的示例,展示了如何在C++中使用pthread创建和管理线程。
首先,确保你的编译器支持C++11或更高版本,因为C++11引入了原生的线程库(
包含头文件:
#include <pthread.h> #include <iostream>
定义线程函数:
void* threadFunction(void* arg) { int threadId = *(static_cast<int*>(arg)); std::cout << "Thread " << threadId << " is running." << std::endl; return nullptr; }
创建线程:
int main() { pthread_t threads[5]; int threadIds[5]; for (int i = 0; i < 5; ++i) { threadIds[i] = i; if (pthread_create(&threads[i], nullptr, threadFunction, &threadIds[i]) != 0) { std::cerr << "Failed to create 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++编译时,需要链接pthread库:
g++ -pthread your_program.cpp -o your_program
如果你更喜欢使用C++11的原生线程库,可以参考以下示例:
包含头文件:
#include <thread> #include <iostream>
定义线程函数:
void threadFunction(int threadId) { std::cout << "Thread " << threadId << " is running." << std::endl; }
创建线程:
int main() { std::thread threads[5]; for (int i = 0; i < 5; ++i) { threads[i] = std::thread(threadFunction, i); } // 等待所有线程完成 for (auto& t : threads) { if (t.joinable()) { t.join(); } } std::cout << "All threads have finished." << std::endl; return 0; }
编译程序: 使用g++编译时,需要启用C++11标准:
g++ -std=c++11 your_program.cpp -o your_program
这两种方法都可以实现多线程编程,选择哪种方法取决于你的需求和个人偏好。C++11的原生线程库提供了更现代和类型安全的接口,而pthread则是一个更底层的库,提供了更多的控制选项。