下面按**“Linux + C++ 配置多线程”**的常见场景,分几种方式给你讲清楚,从最基础到工程常用。
-pthread#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;
}
g++ main.cpp -o main -pthread
✅ 这是最通用、跨平台的方案
适合:
#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
cmake_minimum_required(VERSION 3.10)
project(multithread_demo)
set(CMAKE_CXX_STANDARD 11)
find_package(Threads REQUIRED)
add_executable(demo main.cpp)
target_link_libraries(demo Threads::Threads)
mkdir build && cd build
cmake ..
make
✅ 自动处理 -pthread
#include <thread>
unsigned int n = std::thread::hardware_concurrency();
常用于线程池:
std::vector<std::thread> pool;
for (unsigned i = 0; i < n; ++i)
pool.emplace_back(worker, i);
-pthread症状:
undefined reference to `pthread_create'
int x = 0;
// 多线程同时修改 x ❌
✅ 解决:
std::mutexstd::atomic#include <mutex>
std::mutex mtx;
mtx.lock();
// 临界区
mtx.unlock();
std::asyncstd::condition_variable如果你愿意,可以告诉我:
我可以直接给你一套可跑的完整工程结构。