C++ std::thread 多线程编程入门

C++11 引入了标准线程库 std::thread,大大简化了多线程编程。本文将介绍如何使用 std::thread 实现基本的多线程程序。

1. 创建线程

#include <iostream>
#include <thread>

void say_hello() {
    std::cout << "Hello from thread!" << std::endl;
}

int main() {
    std::thread t(say_hello);
    t.join(); // 等待线程结束
    return 0;
}

2. 使用 Lambda 启动线程

std::thread t([](){
    std::cout << "Hello from lambda thread!" << std::endl;
});
t.join();

3. 线程传参

void print_number(int x) {
    std::cout << "Number: " << x << std::endl;
}

std::thread t(print_number, 42);

4. detach vs join

  • join():阻塞主线程直到子线程完成
  • detach():分离线程,允许其在后台运行

5. 注意事项

  • 使用线程前确保包含 <thread>
  • 避免使用未同步的共享变量
  • 使用互斥锁 std::mutex 保证线程安全

总结

std::thread 是现代 C++ 多线程编程的基础,掌握其用法能为并发编程打下坚实基础。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐