I've created this very small header that allows direct creation of threads from lambdas.
I can't find anything else similar on the net so I want to know whether there are any problems with this that I have not thought of. It is based on tinythread++, but can easily be altered to work with pthread or other threading libraries that can take a void (void*)
(or void* (void*)
) function and a void*
argument for the function to start a thread. Note that this implementation is assuming limited C++0x/11 support, i.e. just lambdas.
#include "tinythread.h"
namespace lthread {
/// implementation details - do not use directly
namespace impl {
template<typename Func>
void use_function_once(void* _f) {
const Func* f = (const Func*)_f;
(*f)();
delete f; // delete - no longer needed
}
template<typename Func>
void use_function(void* _f) {
const Func* f = (const Func*)_f;
(*f)();
}
}
/// Creates a thread based on a temporary function.
/// Copies the function onto the heap for use outside of the local scope, removes from the heap when finished.
template<typename Func>
tthread::thread* new_thread(const Func& f) {
Func* _f = new Func(f); // copy to heap
return new tthread::thread(&impl::use_function_once<Func>,(void*)_f);
}
/// Creates a thread based on a guaranteed persistent function.
/// Does not copy or delete the function.
template<typename Func>
tthread::thread* new_thread(const Func* f) {
return new tthread::thread(&impl::use_function<Func>, (void*)f);
}
}
Example usage:
size_t a = 1;
size_t b = 0;
tthread::thread* t = lthread::new_thread([&] () {
std::cout << "I'm in a thread!\n";
std::cout << "'a' is " << a << std::endl;
b = 1;
});
t->join();
std::cout << "'b' is " << b << std::endl;
delete t;
(*f)();
should throw? You get a leak. – user1095108 Aug 3 '13 at 23:17