项目作者: ku-sourav

项目描述 :
ThreadPool implementation in C++.
高级语言: C++
项目地址: git://github.com/ku-sourav/ThreadPool.git
创建时间: 2019-08-03T15:19:30Z
项目社区:https://github.com/ku-sourav/ThreadPool

开源协议:MIT License

下载


ThreadPool

ThreadPool implementation in C++. The main purpose of creating this project was to learn threadpool. The code is easy to read and understand.
If you don’t know about threadpool. Read here

Compilation

Tested on Linux Machine. Compile using below command

  1. g++ -std=c++11 main.cpp -pthread

Usage

  1. Create a threadpool of three threads

    1. Tpool pool(3);

    It will create three workers which will execute tasks submitted to the threadpool.

  2. Queue a work. If we have a function accepting two integer arguments and returning their sum( e.g - int add(int, int)), we can queue it using

    1. auto fut1 = pool.enq(add, 100, 200);

    You have to pass function name, followed by the arguments accepted by the function. No need to worry about the function signature.
    It returns an appropriate future object(future<int> in the above case). You can use auto to catch the return future object from the threadpool without worrying about the return type.
    To print the result, use get() method of future object.

    1. std::cout << "foo returned: " << fut1.get() << "\n";

    Lets understand another example. Suppose we have a class Test

    1. struct Test{};

    There are two functions - one accepts rvalue reference and another lvalue reference of Test object as args.

    1. void foo(Test&& obj);
    2. void bar(Test& obj);

    You can queue these functions in our threadpool and pass rvalue/lvalue. Threadpool will make sure that the value type of argument is preserved when executing the work.

    1. Test t;
    2. pool.enq(bar, t); //threadpool forwards arg as lvalue
    3. pool.enq(foo, Test()); //threadpool forwards arg as rvalue

    There are more examples in the file main.cpp

    Implementation Overview

    Below is the threadpool class overview with its members.

    1. class Tpool {
    2. using Task = std::function<void(void)>;
    3. public:
    4. Tpool(std::size_t sz);
    5. ~Tpool();
    6. template<typename T, typename ... Args>
    7. auto enq(T&& func, Args&& ... args) -> std::future<decltype(func(std::forward<Args>(args)...))>();
    8. private:
    9. void start();
    10. void stop() noexcept;
    11. std::queue<Task> q;
    12. std::vector<std::thread> workers;
    13. std::mutex mu;
    14. std::condition_variable cv;
    15. bool pstop = false;
    16. std::size_t sz;
    17. };

    License

    THE MIT LICENSE Copyright (c) 2020 Kumar Sourav