线程传参时的问题
  1. 当线程传递为一个可调用的对象时,如果传递临时对象,则此临时对象会立即销毁,线程空间保留的是拷贝后的对象
    #include <iostream>
    #include <thread>
    struct Task {
     void operator()() const {
         std::cout << "Running in thread" << std::endl;
     }
    };
    int main() {
     std::thread t(Task{});  // 注意这里是临时对象 Task{}
     t.join();
    }
    如果可调用对象本身很大,拷贝会带来性能问题,可以使用std::ref包装,传递引用,但需要确保线程运行期间对象的可用性
    Task task;
    std::thread t(std::ref(task));  // 传引用,不复制
    t.join();
RAII版本线程实例代码
class thread_guard
{
    std::thread& t;
public:
    explicit thread_guard(std::thread& t_): t(t_) {}

    ~thread_guard()
    {
        if (t.joinable()) // 1
        {
            t.join(); // 2
        }
    }

    thread_guard(thread_guard const&) = delete; // 3
    thread_guard& operator=(thread_guard const&) = delete;
};

struct func; // 声明,定义在清单2.1中
void f()
{
    int some_local_state = 0;
    func my_func(some_local_state);  // 创建一个可调用对象 my_func
    std::thread t(my_func);          // 启动线程,执行 my_func
    thread_guard g(t);               // 用 thread_guard 保护线程
    do_something_in_current_thread(); // 主线程继续做别的事情
}
join()的本质
  • 如果线程还在跑,join会等待线程跑完
  • 如果线程已经结束,join只是回收线程资源,且立即完成
作者:admin  创建时间:2025-04-29 09:27
最后编辑:admin  更新时间:2025-04-29 09:46