温馨提示×

Linux C++怎么多线程

小樊
39
2026-07-17 06:22:57
栏目: 编程语言

在 Linux 下用 C++ 做多线程,常见有三种方式:POSIX 线程(pthread)C++11 线程库(推荐)、以及 第三方库。下面从最常用到最底层给你讲清楚,并附示例。


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

优点

  • 跨平台(Linux / Windows 都可用)
  • 语法简单、安全
  • 不需要额外安装库

示例:创建两个线程

#include <iostream>
#include <thread>

void func1() {
    std::cout << "Thread 1 running\n";
}

void func2(int x) {
    std::cout << "Thread 2, x = " << x << "\n";
}

int main() {
    std::thread t1(func1);
    std::thread t2(func2, 10);

    t1.join();  // 等待线程结束
    t2.join();

    return 0;
}

编译(Linux)

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

⚠️ 注意:必须加 -pthread


✅ 二、POSIX 线程(pthread,Linux 原生)

如果你写偏底层(如系统编程、嵌入式),可能会看到 pthread

示例

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

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

int main() {
    pthread_t t;
    pthread_create(&t, nullptr, thread_func, nullptr);
    pthread_join(t, nullptr);
    return 0;
}

编译

g++ main.cpp -pthread

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

多线程一定要处理竞态条件

1️⃣ std::mutex(互斥锁)

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

std::mutex mtx;

void func() {
    mtx.lock();
    std::cout << "safe print\n";
    mtx.unlock();
}

int main() {
    std::thread t1(func);
    std::thread t2(func);
    t1.join();
    t2.join();
}

✅ 推荐用 std::lock_guard

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

2️⃣ 条件变量(线程通信)

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

void consumer() {
    std::unique_lock<std::mutex> lock(mtx);
    cv.wait(lock, []{ return ready; });
}

void producer() {
    ready = true;
    cv.notify_one();
}

✅ 四、常见坑(很重要)

线程对象析构前没 join 或 detach

std::thread t(func);
// t.join(); 或 t.detach(); // 必须

多线程同时 cout(要加锁)

误以为多线程一定更快(线程切换也有开销)


✅ 五、如何选择?

场景 推荐
普通 Linux C++ 程序 std::thread
系统 / 嵌入式 pthread
高性能并发 线程池 + 无锁队列
并行计算 OpenMP / TBB

✅ 六、进阶:线程池(如果你需要)

如果你要“大量任务 + 少量线程”,我可以给你一个线程池完整示例


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

  • ✅ 你是 学习 / 项目 / 面试
  • ✅ 是否需要 socket / 多进程 / 高并发
  • ✅ Linux 版本 & gcc 版本?

我可以根据你的场景直接给你最合适的代码。

0