温馨提示×

linux c++配置怎样配线程

小樊
38
2026-10-10 23:57:36
栏目: 编程语言

在 Linux 下用 C++ 配置/使用线程,通常有几种方式,从系统原生到现代 C++ 标准,下面按常见程度给你讲清楚。


一、最推荐:C++11 及以上 std::thread(首选)

1️⃣ 编译配置(很重要)

Linux 下 必须链接 pthread:

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

⚠️ 即使是 std::thread,底层仍然依赖 pthread


2️⃣ 基本用法

#include <iostream>
#include <thread>

void worker(int id) {
    std::cout << "thread " << id << std::endl;
}

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

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

    return 0;
}

3️⃣ 设置线程属性(核心数 / CPU 亲和性)

查看 CPU 核心数

#include <thread>
unsigned int n = std::thread::hardware_concurrency();

二、Linux 原生:pthread(老项目常见)

1️⃣ 编译

g++ main.cpp -pthread

2️⃣ 示例

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

void* thread_func(void* arg) {
    std::cout << "hello pthread" << std::endl;
    return nullptr;
}

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

三、线程池(生产环境推荐)

不要频繁 new thread,用线程池:

简单线程池思路

  • 固定 N 个 worker 线程
  • 任务队列(queue)
  • 条件变量 + 互斥锁

或者直接用库:

  • std::async
  • boost::asio::thread_pool
  • folly::CPUThreadPoolExecutor

四、Linux 特有配置(进阶)

1️⃣ 设置 CPU 亲和性(绑核)

#define _GNU_SOURCE
#include <pthread.h>
#include <sched.h>

cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(0, &cpuset);
pthread_setaffinity_np(pthread_self(), sizeof(cpuset), &cpuset);

2️⃣ 设置线程栈大小

pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, 8 * 1024 * 1024); // 8MB

五、常见坑总结

✅ 一定要 join() 或 detach()
✅ 多线程访问共享变量必须加锁
✅ 不要捕获局部变量引用到线程里
✅ Release 下线程问题更难查


六、你应该选哪种?

场景 推荐
新项目 std::thread
老 C 项目 pthread
高并发服务 线程池
极致性能 绑核 + 无锁

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

  • 你用的是 C++ 版本
  • 是 服务端 / 客户端 / 嵌入式
  • 是否要 高并发 / 低延迟

我可以直接帮你写一套可用的线程配置模板。

0 踩