在C ++ 11中的std :: thread出口上自动调用函数 [英] Invoking a function automatically on std::thread exit in C++11

查看:104
本文介绍了在C ++ 11中的std :: thread出口上自动调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设置一个函数(或lambda函数)的调用以在当前线程退出时自动发生,但是我看不到有什么办法可以与std::thread一起使用,除非我接管了整个任务.线程创建或手动确保每个线程都调用我一直提供的某些特定功能,作为其最后的操作.

I want to set up an invocation of a function (or lambda function) to happen automatically when the current thread exits, but I cannot see any way to do it that works with std::thread unless I take over the entire task of thread creation or manually ensure that every thread calls some particular function that I always provide as its very last operation.

本质上,我希望函数的原型可能类似于以下内容:

Essentially, I want function whose prototype may resemble something like this:

on_thread_exit(const std::function<void()> &func);

将执行必要的任何设置,以确保在调用on_thread_exit的线程最终终止时自动调用给定功能,而无需在线程创建或终止时显式调用任何特定功能.

Which would perform whatever setup was necessary to ensure that the given function was automatically called when the thread which called on_thread_exit eventually terminates, and without requiring any particular functions to be explicitly called at thread creation or termination.

推荐答案

您可以使用thread_local存储来实现,因为C ++ 11应该在线程退出后调用析构函数.您必须确保您的编译器能够正确地支持该编译器.

You can do it using thread_local storage, since C++11 should call the destructors after the thread exits. You'll have to make sure you have a compiler that supports that properly.

#include <stack> 
#include <function>

void on_thread_exit(std::function<void()> func)
{
  class ThreadExiter
  {
    std::stack<std::function<void()>> exit_funcs;
  public:
    ThreadExiter() = default;
    ThreadExiter(ThreadExiter const&) = delete;
    void operator=(ThreadExiter const&) = delete;
    ~ThreadExiter()
    {
      while(!exit_funcs.empty())
      {
        exit_funcs.top()();
        exit_funcs.pop();
      }
    }
    void add(std::function<void()> func)
    {
      exit_funcs.push(std::move(func));
    }   
  };

  thread_local ThreadExiter exiter;
  exiter.add(std::move(func));
}

基本上,此函数创建上述类的thread_local对象.这基本上是静态的,除了在线程退出时被销毁.调用时,它将函数推入向量,并在其破坏时运行函数.

Basically, this function creates a thread_local object of the above class. This is basically static, except is destroyed when the thread exits. When called, it pushes the function onto the vector, and when its destroyed it runs the functions.

您可以通过从任何线程调用on_thread_exit()来使用它,这将创建出口对象,该对象将以与放入线程队列相反的顺序运行您的函数(可以随意修改)

You can use it by calling on_thread_exit() from any thread, which will create the exit object, which will run your function in the reverse order that it was put into the thread queue (feel free to modify as you see fit).

这篇关于在C ++ 11中的std :: thread出口上自动调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆