diff --git a/include/threadpool.h b/include/threadpool.h index 0645885..2bae614 100644 --- a/include/threadpool.h +++ b/include/threadpool.h @@ -27,10 +27,12 @@ public: template std::future add_task(std::function func) { std::lock_guard lock(_mutex); - std::packaged_task pt(func); - std::future fut = pt.get_future(); - _queue.push([&pt]{ pt(); }); - _cv.notify_all(); + std::shared_ptr> pt_ptr = std::make_shared>(func); + std::future fut = pt_ptr->get_future(); + + std::function tf = [pt_ptr] { (*pt_ptr)(); }; + _queue.push(tf); + _cv.notify_one(); return fut; } diff --git a/test/main.cpp b/test/main.cpp index 8b2b777..5d57066 100755 --- a/test/main.cpp +++ b/test/main.cpp @@ -1,6 +1,7 @@ #include "ustring.h" #include "utf.h" #include "logger.h" +#include "threadpool.h" #include #include #include @@ -578,13 +579,8 @@ int main(int argc, char **argv) //::testing::InitGoogleTest(&argc, argv); //return RUN_ALL_TESTS(); + /* const std::size_t threadsCount = 2; - - //int one = 1; - //double two = 2.5; - //ulog.log("one: %, two: %", one, two); - //ulog.log("Hello world!"); - //ulog.log("some string: %", "qwe!"); std::thread threads[threadsCount]; for(std::size_t i = 0; i < threadsCount; ++i) @@ -596,6 +592,24 @@ int main(int argc, char **argv) for(std::size_t i = 0; i < threadsCount; ++i) threads[i].join(); + */ + + threadpool pool(4); + + for (std::size_t i = 0; i < 100; ++i) + { + std::function func = [i]() -> int { + auto id = std::this_thread::get_id(); + std::this_thread::sleep_for(std::chrono::seconds(5)); + ulog.log_info("task % with id %", i, id); + return 0; + }; + + pool.add_task(func); + } + + int n; + std::cin >> n; return 0; }