在 Ubuntu 下配置和使用 C++ 多线程,通常有两种常见方式:
std::thread)(推荐)下面分别说明 环境配置、编译方式、示例代码。
std::thread(推荐)查看 GCC 版本:
g++ --version
sudo apt update
sudo apt install g++ make
main.cpp)#include <iostream>
#include <thread>
void threadFunc(int id) {
std::cout << "Thread " << id << " is running\n";
}
int main() {
std::thread t1(threadFunc, 1);
std::thread t2(threadFunc, 2);
t1.join();
t2.join();
std::cout << "Main thread done\n";
return 0;
}
-pthread)g++ main.cpp -o main -std=c++11 -pthread
运行:
./main
✅ 注意:
-pthread 是必须的(链接线程库)-std=c++11 或更高#include <iostream>
#include <pthread.h>
void* threadFunc(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, threadFunc, &a);
pthread_create(&t2, nullptr, threadFunc, &b);
pthread_join(t1, nullptr);
pthread_join(t2, nullptr);
return 0;
}
g++ pthread_demo.cpp -o pthread_demo -pthread
CMakeLists.txtcmake_minimum_required(VERSION 3.10)
project(ThreadDemo)
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
std::thread 未定义✅ 没加:
-std=c++11
undefined reference to pthread_*✅ 没加:
-pthread
✅ 使用:
#include <mutex>
std::mutex mtx;
std::asyncstd::mutexstd::condition_variablestd::atomic如果你有 具体场景(如线程池、生产者消费者、服务器并发),我可以给你更针对性的示例。