安裝開發工具和庫
使用yum安裝GCC編譯器、glibc開發庫和pthread庫:
sudo yum groupinstall "Development Tools" # 安裝編譯工具鏈
sudo yum install glibc-devel pthread-devel # 安裝多線程相關庫
編寫多線程程序
創建C++文件(如test_threads.cpp
),包含<thread>
頭文件,示例代碼:
#include <iostream>
#include <thread>
void hello() { std::cout << "Hello from thread!" << std::endl; }
int main() {
std::thread t(hello);
t.join();
return 0;
}
編譯程序
使用g++
編譯時添加-std=c++11
(啟用C++11標準,支持多線程)和-pthread
(鏈接線程庫):
g++ -std=c++11 -pthread test_threads.cpp -o test_threads
運行程序
執行生成的可執行文件:
./test_threads
注意:CentOS 8已停止支持,建議升級到CentOS Stream或Ubuntu等長期支持系統。