温馨提示×

ubuntu c++多线程怎么配置

小樊
40
2026-09-17 13:30:51
栏目: 编程语言

在 Ubuntu 下配置和使用 C++ 多线程,通常有两种常见方式:

  1. 使用 C++11 标准线程(std::thread(推荐)
  2. 使用 POSIX 线程(pthread)

下面分别说明 环境配置、编译方式、示例代码


一、使用 C++11 std::thread(推荐)

1. 系统要求

  • Ubuntu 11.04+
  • GCC 4.7+(建议 GCC 7+)

查看 GCC 版本:

g++ --version

2. 安装编译工具

sudo apt update
sudo apt install g++ make

3. 示例代码(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;
}

4. 编译(关键:加 -pthread

g++ main.cpp -o main -std=c++11 -pthread

运行:

./main

注意

  • -pthread 是必须的(链接线程库)
  • -std=c++11 或更高

二、使用 POSIX 线程(pthread)

示例代码

#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

三、CMake 配置(推荐工程化使用)

CMakeLists.txt

cmake_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

四、常见问题

1. 编译报错:std::thread 未定义

✅ 没加:

-std=c++11

2. 运行时报错:undefined reference to pthread_*

✅ 没加:

-pthread

3. 多线程不安全输出混乱

✅ 使用:

#include <mutex>
std::mutex mtx;

五、进阶建议

  • std::async
  • std::mutex
  • std::condition_variable
  • std::atomic

如果你有 具体场景(如线程池、生产者消费者、服务器并发),我可以给你更针对性的示例。

0