温馨提示×

ubuntu c++怎么写多线程

小樊
49
2026-10-05 08:36:07
栏目: 编程语言

在 Ubuntu(Linux)下用 C++ 写多线程,主要有 三种常见方式:


一、推荐方式:C++11 标准线程(std::thread)

✅ 简单、跨平台、现代 C++ 首选

1️⃣ 基本示例

#include <iostream>
#include <thread>

void thread_func(int id) {
    std::cout << "线程 " << id << " 运行中\n";
}

int main() {
    std::thread t1(thread_func, 1);
    std::thread t2(thread_func, 2);

    t1.join();
    t2.join();

    return 0;
}

2️⃣ 编译(Ubuntu)

g++ main.cpp -std=c++11 -pthread
./a.out

⚠️ -pthread 是必须的


二、Linux 原生线程:POSIX Thread(pthread)

✅ 更接近系统层,老项目常见

示例

#include <pthread.h>
#include <iostream>

void* thread_func(void* arg) {
    int id = *(int*)arg;
    std::cout << "线程 " << id << "\n";
    return nullptr;
}

int main() {
    pthread_t t1, t2;
    int a = 1, b = 2;

    pthread_create(&t1, nullptr, thread_func, &a);
    pthread_create(&t2, nullptr, thread_func, &b);

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
}

编译

g++ main.cpp -pthread

三、线程同步(非常重要)

1️⃣ 互斥锁(mutex)

#include <mutex>

std::mutex mtx;

void safe_print() {
    mtx.lock();
    std::cout << "安全输出\n";
    mtx.unlock();
}

或用 RAII:

std::lock_guard<std::mutex> lock(mtx);

2️⃣ 条件变量

std::condition_variable cv;

四、常见问题

❓ 为什么不用 fork?

  • fork 是进程,不是线程
  • 线程共享内存,fork 不共享

❓ 线程数多少合适?

  • CPU 密集型:≈ 核心数
  • IO 密集型:可多于核心数

五、推荐学习路径

  1. std::thread
  2. mutex / lock_guard
  3. condition_variable
  4. async / future

如果你愿意,我可以:

  • 写一个 生产者消费者模型
  • 讲 线程池
  • 对比 多线程 vs 多进程
  • 针对你的 Ubuntu 版本给示例

你现在是学习用还是项目实战?

0 踩