在 CentOS 上写 C++ 多线程程序,一般使用 C++11 标准线程库(std::thread),或者更底层的 POSIX 线程(pthread)。下面我分别给你示例,并说明编译方法。
gcc --version
g++ --version
如果版本太低(低于 4.8),建议升级:
sudo yum install centos-release-scl
sudo yum install devtoolset-9
scl enable devtoolset-9 bash
#include <iostream>
#include <thread>
#include <vector>
using namespace std;
void worker(int id) {
cout << "线程 " << id << " 开始执行" << endl;
}
int main() {
vector<thread> threads;
for (int i = 0; i < 5; ++i) {
threads.emplace_back(worker, i);
}
for (auto& t : threads) {
t.join();
}
cout << "所有线程结束" << endl;
return 0;
}
-pthread)g++ -std=c++11 -pthread main.cpp -o main
./main
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
mutex mtx;
void print(int id) {
mtx.lock();
cout << "线程 " << id << " 正在打印" << endl;
mtx.unlock();
}
int main() {
thread t1(print, 1);
thread t2(print, 2);
t1.join();
t2.join();
}
#include <pthread.h>
#include <iostream>
using namespace std;
void* thread_func(void* arg) {
long id = (long)arg;
cout << "pthread " << id << endl;
return nullptr;
}
int main() {
pthread_t t1, t2;
pthread_create(&t1, nullptr, thread_func, (void*)1);
pthread_create(&t2, nullptr, thread_func, (void*)2);
pthread_join(t1, nullptr);
pthread_join(t2, nullptr);
}
g++ pthread_demo.cpp -o pthread_demo -pthread
-pthread报错类似:
undefined reference to `pthread_create`
✅ 加 -pthread
✅ 使用 -std=c++11 或更高
std::asyncstd::atomicstd::condition_variable如果你愿意,可以告诉我:
我可以直接给你更贴合的代码。