温馨提示×

linux c++如何创建线程

小樊
50
2026-07-05 19:12:00
栏目: 编程语言

在 Linux 下用 C++ 创建线程,常见有三种方式:

  1. POSIX 线程(pthread,最底层、最常用)
  2. C++11 std::thread(推荐,跨平台)
  3. 系统调用 clone(很少直接用)

下面重点讲 pthreadC++11 thread,并给出完整示例。


一、使用 POSIX 线程(pthread)

1️⃣ 头文件

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

2️⃣ 线程函数

void* thread_func(void* arg)
{
    int* val = (int*)arg;
    std::cout << "Thread running, arg = " << *val << std::endl;
    return nullptr;
}

3️⃣ 创建线程

int main()
{
    pthread_t tid;
    int value = 10;

    pthread_create(&tid, nullptr, thread_func, &value);
    pthread_join(tid, nullptr);  // 等待线程结束

    std::cout << "Main thread exit" << std::endl;
    return 0;
}

4️⃣ 编译

g++ thread_pthread.cpp -o thread_pthread -lpthread

特点

  • Linux 原生支持
  • 性能高
  • 接口偏 C,稍显繁琐

二、使用 C++11 std::thread(✅ 强烈推荐)

1️⃣ 头文件

#include <thread>
#include <iostream>

2️⃣ 线程函数

void thread_func(int x)
{
    std::cout << "Thread running, x = " << x << std::endl;
}

3️⃣ 创建线程

int main()
{
    std::thread t(thread_func, 10);
    t.join();  // 等待线程结束

    std::cout << "Main thread exit" << std::endl;
    return 0;
}

4️⃣ 编译

g++ -std=c++11 thread_std.cpp -o thread_std

优点

  • 跨平台(Linux / Windows / macOS)
  • 语法现代、安全
  • 不需要手动链接 pthread

三、线程传参方式对比

pthread

pthread_create(&tid, nullptr, func, (void*)arg);

std::thread

std::thread t(func, arg1, arg2);

四、常见错误

忘记 join / detach

std::thread t(func);
// 程序会直接 terminate

✅ 正确做法:

t.join();
// 或
t.detach();

五、什么时候用哪种?

场景 推荐
新项目 / 跨平台 std::thread
Linux 底层 / 高性能 pthread
学习操作系统原理 pthread

如果你愿意,我可以继续讲:

  • ✅ 线程同步(mutex / condition variable)
  • ✅ 线程池实现
  • ✅ pthread vs std::thread 底层区别
  • ✅ 多线程调试技巧

你想深入哪一块?

0