在 CentOS 上做 C++ 多线程,常见做法有两类:
std::thread) ✅(推荐,跨平台)下面分别说明。
std::thread(推荐)CentOS 一般自带 GCC 4.8+(支持 C++11)
检查版本:
g++ --version
如果是老系统(如 CentOS 6):
yum install gcc-c++
#include <iostream>
#include <thread>
void worker(int id) {
std::cout << "Thread " << id << " running\n";
}
int main() {
std::thread t1(worker, 1);
std::thread t2(worker, 2);
t1.join();
t2.join();
return 0;
}
必须加 -pthread:
g++ main.cpp -o main -std=c++11 -pthread
运行:
./main
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
void worker(int id) {
mtx.lock();
std::cout << "Thread " << id << " in critical section\n";
mtx.unlock();
}
int main() {
std::thread t1(worker, 1);
std::thread t2(worker, 2);
t1.join();
t2.join();
}
适合:
#include <pthread.h>
#include <iostream>
void* worker(void* arg) {
int id = *(int*)arg;
std::cout << "Thread " << id << "\n";
return nullptr;
}
int main() {
pthread_t t1, t2;
int a = 1, b = 2;
pthread_create(&t1, nullptr, worker, &a);
pthread_create(&t2, nullptr, worker, &b);
pthread_join(t1, nullptr);
pthread_join(t2, nullptr);
}
编译:
g++ pthread_demo.cpp -o pthread_demo -pthread
std::thread not member原因:
-std=c++11✅ 解决:
g++ xxx.cpp -std=c++11 -pthread
join()std::threadstd::mutexstd::condition_variablestd::async如果你愿意,我可以:
你现在是 学习 / 项目 / 服务器开发 哪种用途?