温馨提示×

ubuntu怎么写c++多线程

小樊
40
2026-10-02 10:51:51
栏目: 编程语言

在 Ubuntu 下写 C++ 多线程,通常有两种常见方式:

  1. C++11 标准库 <thread>(推荐,简单、跨平台)
  2. POSIX 线程 pthread(Linux 传统方式)

下面分别说明,并给出完整示例。


一、使用 C++11 标准库(推荐)

1️⃣ 安装编译器

Ubuntu 一般都自带 g++,如果没有:

sudo apt update
sudo apt install g++

2️⃣ 示例代码(thread.cpp)

#include <iostream>
#include <thread>

using namespace std;

void threadFunc(int id) {
    cout << "线程 " << id << " 正在运行" << endl;
}

int main() {
    thread t1(threadFunc, 1);
    thread t2(threadFunc, 2);

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

    cout << "主线程结束" << endl;
    return 0;
}

3️⃣ 编译运行

g++ thread.cpp -std=c++11 -pthread -o thread
./thread

⚠️ -pthread 一定要加


二、使用 std::async(更简单)

#include <iostream>
#include <future>

using namespace std;

int compute(int x) {
    return x * x;
}

int main() {
    auto f = async(launch::async, compute, 10);
    cout << "结果: " << f.get() << endl;
}

编译方式相同。


三、使用 POSIX 线程(pthread)

示例(pthread.cpp)

#include <iostream>
#include <pthread.h>
using namespace std;

void* run(void* arg) {
    long id = (long)arg;
    cout << "pthread " << id << endl;
    return nullptr;
}

int main() {
    pthread_t t1, t2;

    pthread_create(&t1, nullptr, run, (void*)1);
    pthread_create(&t2, nullptr, run, (void*)2);

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

编译

g++ pthread.cpp -pthread -o pthread

四、线程同步(简单示例)

使用 mutex

#include <iostream>
#include <thread>
#include <mutex>

mutex mtx;

void print(int id) {
    mtx.lock();
    cout << "线程 " << id << endl;
    mtx.unlock();
}

int main() {
    thread t1(print, 1);
    thread t2(print, 2);
    t1.join();
    t2.join();
}

五、常见错误

❌ 忘了 -pthread
❌ 主线程提前退出(没 join)
❌ 多个线程同时 cout 导致乱序(用 mutex)


如果你愿意,我可以:

  • 写 生产者消费者模型
  • 讲 线程池
  • 讲 原子变量 / 条件变量
  • 用 CMake 管理多线程项目

你想学哪一种?

0 踩