1. 更新系统与安装必要工具
首先,确保CentOS系统为最新状态,避免因软件包过时导致兼容性问题:
sudo yum update
安装开发工具集(包含gcc、g++、make等基础编译工具)和C++标准库依赖:
sudo yum groupinstall "Development Tools"
sudo yum install glibc-devel
安装pthread库(POSIX线程库,C++多线程编程的核心依赖):
sudo yum install pthread-devel
2. 验证编译器与C++11支持
确认g++编译器已安装(CentOS 7及以上版本默认安装):
g++ --version
建议使用GCC 4.8及以上版本(CentOS 7默认GCC 4.8.5支持C++11,CentOS Stream 9及以上版本GCC版本更高)。若需升级GCC,可通过Software Collections (SCL) 或源码编译安装。
3. 编写简单的C++多线程程序
创建一个测试文件(如test_threads.cpp),使用C++11标准库的<thread>实现多线程:
#include <iostream>
#include <thread>
void helloFunction() {
std::cout << "Hello from a thread!" << std::endl;
}
int main() {
std::thread t(helloFunction); // 创建线程
t.join(); // 主线程等待子线程结束
std::cout << "Hello from the main function!" << std::endl;
return 0;
}
进阶示例:创建多个线程并行执行任务(展示线程管理):
#include <iostream>
#include <thread>
#include <vector>
void task(int id) {
std::cout << "Task " << id << " is running in thread " << std::this_thread::get_id() << 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(task, i); // 创建并启动线程
}
for (auto& t : threads) {
t.join(); // 等待所有线程结束
}
std::cout << "All tasks completed." << std::endl;
return 0;
}
4. 编译多线程程序
使用g++编译时,必须添加两个关键选项:
-std=c++11:启用C++11标准(支持<thread>、<mutex>等头文件);-pthread:链接POSIX线程库,定义_REENTRANT宏以确保线程安全。g++ -std=c++11 -pthread test_threads.cpp -o test_threads
5. 运行与验证程序
执行生成的可执行文件,观察输出结果(线程执行顺序可能随机,体现并行性):
./test_threads
预期输出(示例):
Hello from a thread!
Hello from the main function!
Task 0 is running in thread 140123456789000
Task 1 is running in thread 140123448396304
Task 2 is running in thread 140123439903608
Task 3 is running in thread 140123431510912
Task 4 is running in thread 140123423118216
All tasks completed.
6. 基础线程管理与同步(进阶)
std::mutex保护共享资源,避免数据竞争。示例如下:#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx; // 互斥锁
int shared_data = 0;
void increment() {
mtx.lock(); // 加锁
++shared_data;
std::cout << "Thread " << std::this_thread::get_id() << ": shared_data = " << shared_data << std::endl;
mtx.unlock(); // 解锁
}
int main() {
std::thread t1(increment);
std::thread t2(increment);
t1.join();
t2.join();
return 0;
}
std::lock_guard自动管理锁的生命周期,避免忘记解锁:#include <mutex>
#include <thread>
std::mutex mtx;
int counter = 0;
void safe_increment() {
std::lock_guard<std::mutex> lock(mtx); // 构造时加锁,析构时自动解锁
++counter;
}
int main() {
std::thread t1(safe_increment);
std::thread t2(safe_increment);
t1.join();
t2.join();
std::cout << "Counter: " << counter << std::endl;
return 0;
}
7. 系统级优化建议
swappiness值(降低Swap使用频率),提升多线程内存访问性能:echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
sudo sysctl -p
nice命令调整进程优先级(如nice -n -10 ./your_program提升优先级),或通过taskset绑定线程到特定CPU核心(如taskset -c 0,1 ./your_program)。fio工具测试磁盘性能,选择合适的文件系统(如XFS),并开启noatime挂载选项减少元数据操作。net.core.somaxconn增加连接队列长度),使用多队列网卡提升网络吞吐量。