在Linux中,C++程序可以通过多种方式实现多线程。以下是两种常用的方法:
POSIX线程(pthreads)是一种广泛使用的多线程库,适用于Unix-like系统,包括Linux。
#include <iostream>
#include <pthread.h>
// 线程函数
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
<thread>
C++11引入了标准库中的多线程支持,使用<thread>
头文件可以更方便地实现多线程编程。
#include <iostream>
#include <thread>
#include <vector>
// 线程函数
void thread_function(int thread_id) {
std::cout << "Thread " << thread_id << " is running." << std::endl;
}
int main() {
const int num_threads = 5;
std::vector<std::thread> 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
<thread>
:提供了更现代和简洁的多线程编程接口,推荐在C++11及以上版本中使用。选择哪种方法取决于你的具体需求和项目环境。