温馨提示×

ubuntu c++如何写多线程

小樊
35
2026-09-02 08:57:55
栏目: 编程语言

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

  1. C++11 标准线程(std::thread)✅ 推荐
  2. POSIX 线程(pthread)
  3. 第三方库(如 Boost.Thread)

下面重点讲 C++11 的写法,最常用也最现代。


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

1️⃣ 基本示例

#include <iostream>
#include <thread>

void worker(int id) {
    std::cout << "Thread " << id << " is running\n";
}

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

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

    std::cout << "Main thread done\n";
    return 0;
}

2️⃣ 编译(Ubuntu)

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

⚠️ 必须加 -pthread


二、线程同步(避免数据竞争)

1️⃣ 使用 std::mutex

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

std::mutex mtx;
int counter = 0;

void increment() {
    for (int i = 0; i < 100000; ++i) {
        std::lock_guard<std::mutex> lock(mtx);
        ++counter;
    }
}

int main() {
    std::thread t1(increment);
    std::thread t2(increment);

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

    std::cout << "Counter = " << counter << std::endl;
}

三、使用 Lambda 创建线程

std::thread t([] {
    std::cout << "Lambda thread\n";
});
t.join();

四、POSIX 线程(pthread,传统方式)

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

void* worker(void* arg) {
    std::cout << "pthread\n";
    return nullptr;
}

int main() {
    pthread_t t;
    pthread_create(&t, nullptr, worker, nullptr);
    pthread_join(t, nullptr);
}

编译:

g++ pthread_demo.cpp -pthread

五、常见坑(Ubuntu 下)

✅ 必须加 -pthread
✅ 不要忘记 join()detach()
✅ 多线程访问共享变量要加锁
std::cout 本身不是线程安全的(建议加锁)


六、进阶方向

  • std::async
  • std::condition_variable
  • 线程池
  • 原子操作 std::atomic

如果你愿意,我可以:

  • 写一个 线程池示例
  • Ubuntu 多核 CPU 调度
  • 对比 C++ vs Python 多线程

你现在是做 服务器 / 算法 / 嵌入式 哪一块?

0