|
|
@ -2,11 +2,12 @@ |
|
|
|
#include <functional> |
|
|
|
#include "tiny_pool.h" |
|
|
|
|
|
|
|
class TinyPool { |
|
|
|
class TinyPool { // OOP for tiny_thread_pool
|
|
|
|
pool_t *pool; |
|
|
|
static void wrap_c_func(void *func) { |
|
|
|
(*static_cast<std::function<void()>*>(func))(); |
|
|
|
free(func); |
|
|
|
static void wrap_c_func(void *func) { // wrap std::function as c-style function ptr
|
|
|
|
auto func_ptr = static_cast<std::function<void()>*>(func); |
|
|
|
(*func_ptr)(); |
|
|
|
delete func_ptr; // free lambda function
|
|
|
|
} |
|
|
|
|
|
|
|
public: |
|
|
@ -17,25 +18,22 @@ public: |
|
|
|
explicit TinyPool(uint32_t size) { pool = tiny_pool_create(size); } |
|
|
|
|
|
|
|
template <typename Func, typename ...Args> |
|
|
|
auto submit(Func &&func, Args &&...args) -> std::future<decltype(func(args...))>; |
|
|
|
auto submit(Func &&func, Args &&...args) -> std::future<decltype(func(args...))> { // submit new task
|
|
|
|
std::function<decltype(func(args...))()> wrap_func = std::bind( |
|
|
|
std::forward<Func>(func), std::forward<Args>(args)... // wrap as a function without params
|
|
|
|
); |
|
|
|
auto func_ptr = std::make_shared< |
|
|
|
std::packaged_task<decltype(func(args...))()> // function task as shared ptr
|
|
|
|
>(wrap_func); |
|
|
|
tiny_pool_submit(pool, TinyPool::wrap_c_func, (void*)( // submit with thread pool interface
|
|
|
|
new std::function<void()> ( |
|
|
|
[func_ptr]() { (*func_ptr)(); } // create lambda for running task
|
|
|
|
) |
|
|
|
)); |
|
|
|
return func_ptr->get_future(); // return future object
|
|
|
|
} |
|
|
|
}; |
|
|
|
|
|
|
|
template <typename Func, typename ...Args> |
|
|
|
auto TinyPool::submit(Func &&func, Args &&...args) -> std::future<decltype(func(args...))> { |
|
|
|
std::function<decltype(func(args...))()> wrap_func = std::bind( |
|
|
|
std::forward<Func>(func), std::forward<Args>(args)... |
|
|
|
); |
|
|
|
auto func_ptr = std::make_shared< |
|
|
|
std::packaged_task<decltype(func(args...))()> |
|
|
|
>(wrap_func); |
|
|
|
tiny_pool_submit(pool, TinyPool::wrap_c_func, (void*)( |
|
|
|
new std::function<void()> ( |
|
|
|
[func_ptr]() { (*func_ptr)(); } |
|
|
|
) |
|
|
|
)); |
|
|
|
return func_ptr->get_future(); |
|
|
|
} |
|
|
|
|
|
|
|
/// ------------------------------------ start test ------------------------------------
|
|
|
|
|
|
|
|
#include <iostream> |
|
|
|