温馨提示×

ubuntu c++多线程怎么写

小樊
34
2026-09-14 13:05:26
栏目: 编程语言

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

  1. C++11 标准线程(std::thread ✅ 推荐
  2. POSIX 线程(pthread (偏底层,老项目常见)

下面分别给你示例,从简单到实用。


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

1️⃣ 基本示例

#include <iostream>
#include <thread>

void hello(int id) {
    std::cout << "Hello from thread " << id << std::endl;
}

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

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

    return 0;
}

2️⃣ 编译(Ubuntu)

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

⚠️ -pthread 必须加


二、线程间共享数据(加锁)

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

std::mutex mtx;
int count = 0;

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

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

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

    std::cout << "count = " << count << std::endl;
    return 0;
}

三、使用 condition_variable(线程通信)

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

std::mutex mtx;
std::condition_variable cv;
bool ready = false;

void worker() {
    std::unique_lock<std::mutex> lock(mtx);
    cv.wait(lock, [] { return ready; });
    std::cout << "Worker started\n";
}

int main() {
    std::thread t(worker);

    std::this_thread::sleep_for(std::chrono::seconds(1));
    {
        std::lock_guard<std::mutex> lock(mtx);
        ready = true;
    }
    cv.notify_all();

    t.join();
}

四、POSIX 线程(pthread,了解即可)

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

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

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

编译:

g++ pthread_demo.cpp -pthread

五、常见注意点(很重要)

✅ 必须 join()detach()
✅ 避免数据竞争(用 mutex
✅ 不要返回局部变量引用
✅ 多线程调试可用:

gdb ./demo
thread apply all bt

如果你愿意,可以告诉我:

  • CPU 密集 还是 IO 密集
  • 要不要 线程池
  • 是否需要 信号量 / 原子变量

我可以直接给你一套可运行的工程模板。

0