Reputation: 2337
I am trying to create a C++ function that takes any function with any number of arguments and pass it to std::thread
to start a thread with it.
#include <iostream>
#include <thread>
#define __PRETTY_FUNCTION__ __FUNCSIG__
void runFunctionInThread(void(*f)()) { std::thread t(f); t.join(); }
void runFunctionInThread(void(*f)(int), int value) { std::thread t(f, value); t.join(); }
void runFunctionInThread(void(*f)(int, int), int value1, int value2) { std::thread t(f, value1, value2); t.join(); }
void isolatedFunc1() { std::cout << __PRETTY_FUNCTION__ << "\n"; }
void isolatedFunc2(int value) { std::cout << __PRETTY_FUNCTION__ << " value is " << value << "\n"; }
void isolatedFunc3(int value1, int value2) { std::cout << __PRETTY_FUNCTION__ << " value1+value2 is " << value1 + value2 << "\n"; }
int main() {
runFunctionInThread(&isolatedFunc1);
runFunctionInThread(&isolatedFunc2, 2);
runFunctionInThread(&isolatedFunc3, 3, 3);
}
Is there anyway to create a single runFunctionInThread
function that works for any function with any number of arguments and any type?
Upvotes: 0
Views: 168
Reputation: 598011
Use a variadic template with perfect forwarding of its parameters, eg:
#include <iostream>
#include <thread>
#define __PRETTY_FUNCTION__ __FUNCSIG__
template<class Function, class... Args>
void runFunctionInThread(Function f, Args&&... args) {
std::thread t(f, std::forward<Args>(args)...);
t.detach();
}
void isolatedFunc1() { std::cout << __PRETTY_FUNCTION__ << "\n"; }
void isolatedFunc2(int value) { std::cout << __PRETTY_FUNCTION__ << " value is " << value << "\n"; }
void isolatedFunc3(int value1, int value2) { std::cout << __PRETTY_FUNCTION__ << " value1+value2 is " << value1 + value2 << "\n"; }
int main()
{
runFunctionInThread(&isolatedFunc1);
runFunctionInThread(&isolatedFunc2, 2);
runFunctionInThread(&isolatedFunc3, 3, 3);
}
However, this is fairly redundant since std::thread
can handle this directly for you, so you don't need runFunctionInThread()
at all, eg:
int main()
{
std::thread(&isolatedFunc1).detach();
std::thread(&isolatedFunc2, 2).detach();
std::thread(&isolatedFunc3, 3, 3).detach();
}
Upvotes: 1