diff --git a/Makefile b/Makefile index a830a6e..4e455b0 100644 --- a/Makefile +++ b/Makefile @@ -10,8 +10,8 @@ OS = linux # C++ compier CXX = g++ -CXXFLAGS = -MMD -c -g -Og -Wall -Werror -std=c++11 -Iinclude -Isrc/asm/include -fno-strict-aliasing #-fsanitize=thread -fPIE -LDFLAGS = -lgtest #-ltsan -pie +CXXFLAGS = -MMD -c -g -Og -Wall -Werror -std=c++11 -Iinclude -Isrc/asm/include -fno-strict-aliasing -fsanitize=thread -fPIE +LDFLAGS = -lgtest -ltsan -pie # Archiver AR = ar diff --git a/include/threadpool.h b/include/threadpool.h index 2bae614..c218425 100644 --- a/include/threadpool.h +++ b/include/threadpool.h @@ -30,11 +30,20 @@ public: 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); + _queue.push([pt_ptr] { (*pt_ptr)(); }); _cv.notify_one(); return fut; } + + template std::future add_task(R(*pfn)(Args...), Args... args) + { + return add_task(std::bind(pfn, args...)); + } + + template std::future add_task(R(C::*pfn)(Args...), C* cPtr, Args... args) + { + return add_task(std::bind(pfn, cPtr, args...)); + } private: void worker_func(); diff --git a/test/main.cpp b/test/main.cpp index 5d57066..e596009 100755 --- a/test/main.cpp +++ b/test/main.cpp @@ -574,6 +574,20 @@ void func(std::size_t n) std::cout << "end of thread " << n << std::endl; } +int geti(int i) +{ + return i; +} + +class foo +{ +public: + int bar(int n) + { + return n; + } +}; + int main(int argc, char **argv) { //::testing::InitGoogleTest(&argc, argv); @@ -594,22 +608,21 @@ int main(int argc, char **argv) threads[i].join(); */ - threadpool pool(4); + threadpool pool(4); + std::vector> vec; - 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; + foo f; + for (std::size_t i = 0; i < 100; ++i) + { + //std::future fut = pool.add_task([i] { return i; }); + std::future fut = pool.add_task(&foo::bar, &f, (int)i); + vec.push_back(std::move(fut)); + } + + for(std::size_t i = 0; i < 100; ++i) + { + std::cout << "res[" << i << "] = " << vec[i].get() << std::endl; + } return 0; }