在CentOS系統中,使用C++實現多線程主要依賴于POSIX線程庫(pthread)。以下是一個簡單的示例,展示了如何在C++中使用pthread創建和管理線程。
gcc
和g++
編譯器。如果沒有,請使用以下命令安裝:sudo yum install gcc g++
multithread_example.cpp
的文件,并添加以下代碼:#include <iostream>
#include <pthread.h>
// 線程函數
void* thread_function(void* arg) {
int thread_id = *static_cast<int*>(arg);
std::cout << "Hello from thread " << 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;
int result = pthread_create(&threads[i], nullptr, thread_function, &thread_ids[i]);
if (result != 0) {
std::cerr << "Error creating thread "<< i << ": " << strerror(result) << std::endl;
return 1;
}
}
// 等待線程結束
for (int i = 0; i < num_threads; ++i) {
pthread_join(threads[i], nullptr);
}
return 0;
}
g++
編譯器編譯代碼:g++ -o multithread_example multithread_example.cpp -pthread
注意:在編譯命令中添加-pthread
選項,以便鏈接pthread庫。
./multithread_example
這將創建5個線程,每個線程都會輸出一條消息。
這只是一個簡單的示例,實際應用中可能需要處理更多的線程同步和通信問題。你可以查閱pthread庫的相關文檔以獲取更多信息。