I need to wrap std::thread to do some processing (inside the new thread) before the user function runs.
At the moment I'm achieving this via a helper function, but that's a bit annoying.
How can I convert wrapThreadHelper into a lambda inside wrapThread while keeping the perfect forwarding semantics?
#include <functional>
#include <iostream>
#include <string>
#include <thread>
using namespace std;
struct Foo
{
void bar()
{
cout << "bar is running" << endl;
}
};
template <class F, class... Args>
void wrapThreadHelper(F &&f, Args &&...args)
{
cout << "preparing the thread..." << endl;
std::invoke(std::forward<F>(f), std::forward<Args>(args)...);
cout << "cleaning the thread..." << endl;
}
template <class F, class... Args>
std::thread wrapThread(F &&f, Args &&...args)
{
return std::thread(&wrapThreadHelper<F, Args...>, std::forward<F>(f), std::forward<Args>(args)...);
}
int main()
{
Foo foo;
std::thread t1 = wrapThread(&Foo::bar, std::ref(foo));
std::thread t2 = wrapThread([] { cout << "lambda is running..."; });
t1.join();
t2.join();
return 0;
}
I would like to delete wrapThreadHelper and convert wrapThread into something like this:
template <class F, class... Args>
std::thread wrapThread(F &&f, Args &&...args)
{
return std::thread([]() {
cout << "preparing the thread..." << endl;
std::invoke(std::forward<F>(f), std::forward<Args>(args)...);
cout << "cleaning the thread..." << endl;
});
}