You can do this with the thread_local repository, since C ++ 11 should call destructors after the thread exits. You must make sure that you have the appropriate compiler.
#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)); }
Basically, this function creates a thread_local object of the specified class. This is mostly static, except that it is destroyed when the stream exits. When it is called, it pushes the function onto the vector, and when it destroys it, it performs the functions.
You can use it by calling on_thread_exit() from any thread that will create an exit object that will run your function in the reverse order so that it is placed in the thread queue (feel free to modify as you like).
source share