在CentOS環境下,使用C++實現多線程主要依賴于POSIX線程庫(pthread)。以下是一個簡單的示例,展示了如何在CentOS環境下使用C++和pthread庫創建多線程程序。
首先,確保已經安裝了gcc編譯器。如果沒有安裝,可以使用以下命令安裝:
sudo yum install gcc
接下來,創建一個名為multithread_example.cpp
的文件,并添加以下代碼:
#include <iostream>
#include <pthread.h>
// 線程函數
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])) {
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++ -o multithread_example multithread_example.cpp -pthread
最后,運行編譯后的程序:
./multithread_example
這個示例將創建5個線程,每個線程都會輸出其線程ID。注意,在編譯時需要添加-pthread
選項,以便鏈接pthread庫。