在 Ubuntu 上配置和使用 C++ 多线程,一般涉及三件事:
<thread> 标准库-pthread)下面一步一步说明。
sudo apt update
sudo apt upgrade
sudo apt install g++ build-essential
验证:
g++ --version
main.cpp#include <iostream>
#include <thread>
void hello(int id) {
std::cout << "Hello from thread " << id << std::endl;
}
int main() {
std::thread t1(hello, 1);
std::thread t2(hello, 2);
t1.join();
t2.join();
std::cout << "Main thread done" << std::endl;
return 0;
}
g++ -std=c++11 -pthread main.cpp -o main
或者:
g++ -std=c++14 -pthread main.cpp -o main
./main
-pthread可能会出现:
terminate called after throwing an instance of 'std::system_error'
✅ 解决:加 -pthread
如果是稍大一点的项目,建议用 CMake。
CMakeLists.txtcmake_minimum_required(VERSION 3.10)
project(multithread_demo)
set(CMAKE_CXX_STANDARD 11)
add_executable(main main.cpp)
find_package(Threads REQUIRED)
target_link_libraries(main Threads::Threads)
mkdir build
cd build
cmake ..
make
./main
如果你想直接用 C 风格线程:
#include <pthread.h>
编译:
g++ main.cpp -pthread
但 推荐使用 C++ <thread>,更安全、现代。
gdb ./main
或检查线程:
htop
如果你有具体需求(如线程池、互斥锁、条件变量、生产消费模型),可以告诉我,我可以直接给你完整示例。