├── .gitignore ├── CMakeLists.txt ├── LICENSE ├── README.md ├── affinity.patch ├── example └── main.cpp └── include ├── SafeQueue.h └── ThreadPool.h /.gitignore: -------------------------------------------------------------------------------- 1 | # Build 2 | #VS 3 | .vs/ 4 | Debug/ 5 | Release/ 6 | # Netbeans 7 | nbproject/ 8 | *.user 9 | *.filters 10 | *.vcxproj 11 | *.sln 12 | 13 | # Cmake 14 | build 15 | CMakeCache.txt 16 | CMakeFiles 17 | CMakeScripts 18 | Makefile 19 | cmake_install.cmake 20 | install_manifest.txt 21 | CTestTestfile.cmake 22 | 23 | # Compiled Object files 24 | *.slo 25 | *.lo 26 | *.o 27 | *.obj 28 | !assets/models/*/*.obj 29 | 30 | # Precompiled Headers 31 | *.gch 32 | *.pch 33 | 34 | # Compiled Dynamic libraries 35 | *.so 36 | *.dylib 37 | *.dll 38 | 39 | # Fortran module files 40 | *.mod 41 | *.smod 42 | 43 | # Compiled Static libraries 44 | *.lai 45 | *.la 46 | *.a 47 | *.lib 48 | 49 | # Executables 50 | *.exe 51 | *.out 52 | *.app 53 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # CMake entry point 2 | cmake_minimum_required (VERSION 3.5) 3 | project (thread-pool) 4 | 5 | ## Add headers files 6 | include_directories ( 7 | include/ 8 | ) 9 | 10 | set(HEADERS include/SafeQueue.h include/ThreadPool.h) 11 | 12 | set(SOURCES example/main.cpp) 13 | 14 | SET(CMAKE_CXX_FLAGS -pthread) 15 | 16 | add_compile_options( 17 | -std=c++11 18 | # -D_DEBUG 19 | # -g 20 | ) 21 | 22 | # main.cpp 23 | add_executable(main ${HEADERS} ${SOURCES}) 24 | target_link_libraries(main) 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Mariano Trebino 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Table of Contents 2 |  [Introduction](https://github.com/mtrebi/thread-pool/blob/master/README.md#introduction)
3 |  [Build instructions](https://github.com/mtrebi/thread-pool/blob/master/README.md#build-instructions)
4 |  [Thread pool](https://github.com/mtrebi/thread-pool/blob/master/README.md#thread-pool)
5 |         [Queue](https://github.com/mtrebi/thread-pool/blob/master/README.md#queue)
6 |         [Submit function](https://github.com/mtrebi/thread-pool/blob/master/README.md#submit-function)
7 |         [Thread worker](https://github.com/mtrebi/thread-pool/blob/master/README.md#thread-worker)
8 |  [Usage example](https://github.com/mtrebi/thread-pool/blob/master/README.md#usage-example)
9 |         [Use case#1](https://github.com/mtrebi/thread-pool#use-case-1)
10 |         [Use case#2](https://github.com/mtrebi/thread-pool#use-case-2)
11 |         [Use case#3](https://github.com/mtrebi/thread-pool#use-case-3)
12 |  [Future work](https://github.com/mtrebi/thread-pool/blob/master/README.md#future-work)
13 |  [References](https://github.com/mtrebi/thread-pool/blob/master/README.md#references)
14 | 15 | # Introduction: 16 | 17 | A [thread pool](https://en.wikipedia.org/wiki/Thread_pool) is a technique that allows developers to exploit the concurrency of modern processors in an **easy** and **efficient** manner. It's easy because you send "work" to the pool and somehow this work gets done without blocking the main thread. It's efficient because threads are not initialized each time we want the work to be done. Threads are initialized once and remain inactive until some work has to be done. This way we minimize the overhead. 18 | 19 | There are many more Thread pool implementations in C++, many of them are probably better (safer, faster...) than mine. However,I believe my implementation are **very straightforward and easy to understand**. 20 | 21 | __Disclaimer: Please Do not use this project in a professional environment. It may contain bugs and/or not work as expected.__ I did this project to learn how C++11 Threads work and provide an easy way for other people to understand it too. 22 | 23 | # Build instructions: 24 | 25 | This project has been developed using Netbeans and Linux but it should work on Windows, MAC OS and Linux. It can be easily build using CMake and different other generators. The following code can be used to generate the VS 2017 project files: 26 | 27 | ```c 28 | // VS 2017 29 | cd 30 | mkdir build 31 | cd build/ 32 | cmake .. "Visual Studio 15 2017 Win64" 33 | ``` 34 | 35 | Then, from VS you can edit and execute the project. Make sure that __main project is set up as the startup project__ 36 | 37 | If you are using Linux, you need to change the generator (use the default) and execute an extra operation to actually make it executable: 38 | 39 | ```c 40 | // Linux 41 | cd 42 | mkdir build 43 | cd build/ 44 | cmake .. 45 | make 46 | ``` 47 | 48 | # Thread pool 49 | 50 | The way that I understand things better is with images. So, let's take a look at the image of thread pool given by Wikipedia: 51 | 52 |

53 | 54 | As you can see, we have three important elements here: 55 | * *Tasks Queue*. This is where the work that has to be done is stored. 56 | * *Thread Pool*. This is set of threads (or workers) that continuously take work from the queue and do it. 57 | * *Completed Tasks*. When the Thread has finished the work we return "something" to notify that the work has finished. 58 | 59 | ## Queue 60 | 61 | We use a queue to store the work because it's the more sensible data structure. We want the work to be **started** in the same order that we sent it. However, this queue is a little bit **special**. As I said in the previous section, threads are continuously (well, not really, but let's assume that they are) querying the queue to ask for work. When there's work available, threads take the work from the queue and do it. What would happen if two threads try to take the same work at the same time? Well, the program would crash. 62 | 63 | To avoid these kinds of problems, I implemented a wrapper over the standard C++ Queue that uses mutex to restrict the concurrent access. Let's see a small sample of the SafeQueue class: 64 | 65 | ```c 66 | void enqueue(T& t) { 67 | std::unique_lock lock(m_mutex); 68 | m_queue.push(t); 69 | } 70 | 71 | ``` 72 | To enqueue the first thing we do is lock the mutex to make sure that no one else is accessing the resource. Then, we push the element to the queue. When the lock goes out of scopes it gets automatically released. Easy, huh? This way, we make the Queue thread-safe and thus we don't have to worry many threads accessing and/or modifying it at the same "time". 73 | 74 | ## Submit function 75 | 76 | The most important method of the thread pool is the one responsible of adding work to the queue. I called this method **submit**. It's not difficult to understand how it works but its implementation can seem scary at first. Let's think about **what** should do and after that we will worry about **how** to do it. What: 77 | * Accept any function with any parameters. 78 | * Return "something" immediately to avoid blocking main thread. This returned object should **eventually** contain the result of the operation. 79 | 80 | Cool, let's see **how** we can implement it. 81 | 82 | ### Submit implementation 83 | 84 | The complete submit functions looks like this: 85 | 86 | ```c 87 | // Submit a function to be executed asynchronously by the pool 88 | template 89 | auto submit(F&& f, Args&&... args) -> std::future { 90 | // Create a function with bounded parameters ready to execute 91 | std::function func = std::bind(std::forward(f), std::forward(args)...); 92 | // Encapsulate it into a shared ptr in order to be able to copy construct / assign 93 | auto task_ptr = std::make_shared>(func); 94 | 95 | // Wrap packaged task into void function 96 | std::function wrapper_func = [task_ptr]() { 97 | (*task_ptr)(); 98 | }; 99 | 100 | // Enqueue generic wrapper function 101 | m_queue.enqueue(wrapperfunc); 102 | 103 | // Wake up one thread if its waiting 104 | m_conditional_lock.notify_one(); 105 | 106 | // Return future from promise 107 | return task_ptr->get_future(); 108 | } 109 | ``` 110 | 111 | Nevertheless, we're going to inspect line by line what's going on in order to fully understand how it works. 112 | 113 | #### Variadic template function 114 | 115 | ```c 116 | template 117 | ``` 118 | 119 | This means that the next statement is templated. The first template parameter is called F (our function) and second one is a parameter pack. A parameter pack is a special template parameter that can accept zero or more template arguments. It is, in fact, a way to express a variable number of arguments in a template. A template with at least one parameter pack is called **variadic template** 120 | 121 | Summarizing, we are telling the compiler that our submit function is going to take one generic parameter of type F (our function) and a parameter pack Args (the parameters of the function F). 122 | 123 | #### Function declaration 124 | 125 | ```c 126 | auto submit(F&& f, Args&&... args) -> std::future { 127 | ``` 128 | 129 | This may seem weird but, it's not. A function, in fact, can be declared using two different syntaxes. The following is the most well known: 130 | 131 | ```c 132 | return-type identifier ( argument-declarations... ) 133 | ``` 134 | 135 | But, we can also declare the function like this: 136 | 137 | ```c 138 | auto identifier ( argument-declarations... ) -> return_type 139 | ``` 140 | 141 | Why two syntaxes? Well, imagine that you have a function that has a return type that depends on the input parameters of the function. Using the first syntax you can't declare that function without getting a compiler error since you would be using a variable in the return type that has not been declared yet (because the return type declaration goes before the parameters type declaration). 142 | 143 | Using the second syntax you can declare the function to have return type **auto** then, using the -> you can declare the return type depending on the arguments of the functions that have been declared previously. 144 | 145 | Now, let's inspect the parameters of the submit function. When the type of a parameter is declared as **T&&** for some deducted type T that parameter is a **universal reference**. This term was coined by [Scott Meyers](https://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers) because **T&&** can also mean r-value reference. However, in the context of type deduction, it means that it can be bound to both l-values and r-values, unlike l-value references that can only be bound to non-const objects (they bind only to modifiable lvalues) and r-value references (they bind only to rvalues). 146 | 147 | 148 | The return type of the function is of type **std::future**. An std::future is a special type that provides a mechanism to access the result of asynchronous operations, in our case, the result of executing a specific function. This makes sense with what we said earlier. 149 | 150 | Finally, the template type of std::future is **decltype(f(args...))**. Decltype is a special C++ keyword that inspects the declared type of an entity or the type and value category of an expression. In our case, we want to know the return type of the function _f_, so we give decltype our generic function _f_ and the parameter pack _args_. 151 | 152 | #### Function body 153 | 154 | ```c 155 | // Create a function with bounded parameters ready to execute 156 | std::function func = std::bind(std::forward(f), std::forward(args)...); 157 | ``` 158 | 159 | There are many many things happening here. First of all, the **std::bind(F, Args)** is a function that creates a wrapper for F with the given Args. Caling this wrapper is the same as calling F with the Args that it has been bound. Here, we are simply calling bind with our generic function _f_ and the parameter pack _args_ but using another wrapper **std::forward(t)** for each parameter. This second wrapper is needed to achieve perfect forwarding of universal references. 160 | The result of this bind call is a **std::function**. The std::function is a C++ object that encapsulates a function. It allows you to execute the function as if it were a normal function calling the operator() with the required parameters BUT, because it is an object, you can store it, copy it and move it around. The template type of any std::function is the signature of that function: std::function< return-type (arguments)>. In this case, we already know how to get the return type of this function using decltype. But, what about the arguments? Well, because we bound all arguments _args_ to the function _f_ we just have to add an empty pair of parenthesis that represents an empty list of arguments: **decltype(f(args...))()**. 161 | 162 | 163 | ```c 164 | // Encapsulate it into a shared ptr in order to be able to copy construct / assign 165 | auto task_ptr = std::make_shared>(func); 166 | ``` 167 | 168 | The next thing we do is we create a **std::packaged_task(t)**. A packaged_task is a wrapper around a function that can be executed asynchronously. It's result is stored in a shared state inside an std::future object. The templated type T of an std::packaged_task(t) is the type of the function _t_ that is wrapping. Because we said it before, the signature of the function _f_ is **decltype(f(args...))()** that is the same type of the packaged_task. Then, we just wrap again this packaged task inside a **std::shared_ptr** using the initialize function **std::make_shared**. 169 | 170 | ```c 171 | // Wrap packaged task into void function 172 | std::function wrapperfunc = [task_ptr]() { 173 | (*task_ptr)(); 174 | }; 175 | 176 | ``` 177 | 178 | Again, we create a std:.function, but, note that this time its template type is **void()**. Independently of the function _f_ and its parameters _args_ this _wrapperfunc_ the return type will always be **void**. Since all functions _f_ may have different return types, the only way to store them in a container (our Queue) is wrapping them with a generic void function. Here, we are just declaring this _wrapperfunc_ to execute the actual task _taskptr_ that will execute the bound function _func_. 179 | 180 | ```c 181 | // Enqueue generic wrapper function 182 | m_queue.enqueue(wrapperfunc); 183 | ``` 184 | 185 | We enqueue this _wrapperfunc_. 186 | 187 | ```c 188 | // Wake up one thread if its waiting 189 | m_conditional_lock.notify_one(); 190 | ``` 191 | 192 | Before finishing, we wake up one thread in case it is waiting. 193 | 194 | ```c 195 | // Return future from promise 196 | return task_ptr->get_future(); 197 | ``` 198 | 199 | And finally, we return the future of the packaged_task. Because we are returning the future that is bound to the packaged_task _taskptr_ that, at the same time, is bound with the function _func_, executing this _taskptr_ will automatically update the future. Because we wrapped the execution of the _taskptr_ with a generic wrapper function, is the execution of _wrapperfunc_ that, in fact, updates the future. Aaaaand. since we enqueued this wrapper function, it will be executed by a thread after being dequeued calling the operator(). 200 | 201 | 202 | ## Thread worker 203 | 204 | Now that we understand how the submit method works, we're going to focus on how the work gets done. Probably, the simplest implementation of a thread worker could be using polling: 205 | 206 | Loop 207 | If Queue is not empty 208 | Dequeue work 209 | Do it 210 | 211 | This looks alright but it's **not very efficient**. Do you see why? What would happen if there is no work in the Queue? The threads would keep looping and asking all the time: Is the queue empty? 212 | 213 | The more sensible implementation is done by "sleeping" the threads until some work is added to the queue. As we saw before, as soon as we enqueue work, a signal **notify_one()** is sent. This allows us to implement a more efficient algorithm: 214 | 215 | Loop 216 | If Queue is empty 217 | Wait signal 218 | Dequeue work 219 | Do it 220 | 221 | This signal system is implemented in C++ with **conditional variables**. Conditional variables are always bound to a mutex, so I added a mutex to the thread pool class just to manage this. The final code of a worker looks like this: 222 | 223 | ```c 224 | void operator()() { 225 | std::function func; 226 | bool dequeued; 227 | while (!m_pool->m_shutdown) { 228 | { 229 | std::unique_lock lock(m_pool->m_conditional_mutex); 230 | if (m_pool->m_queue.empty()) { 231 | m_pool->m_conditional_lock.wait(lock); 232 | } 233 | dequeued = m_pool->m_queue.dequeue(func); 234 | } 235 | if (dequeued) { 236 | func(); 237 | } 238 | } 239 | } 240 | 241 | ``` 242 | 243 | The code is really easy to understand so I am not going to explain anything. The only thing to note here is that, _func_ is our wrapper function declared as: 244 | 245 | ```c 246 | std::function wrapperfunc = [task_ptr]() { 247 | (*task_ptr)(); 248 | }; 249 | 250 | ``` 251 | 252 | So, executing this function will automatically update the future. 253 | 254 | # Usage example 255 | 256 | Creating the thread pool is as easy as: 257 | 258 | ```c 259 | // Create pool with 3 threads 260 | ThreadPool pool(3); 261 | 262 | // Initialize pool 263 | pool.init(); 264 | ``` 265 | 266 | When we want to shutdown the pool just call: 267 | 268 | ```c 269 | // Shutdown the pool, releasing all threads 270 | pool.shutdown() 271 | ``` 272 | 273 | Ff we want to send some work to the pool, after we have initialized it, we just have to call the submit function: 274 | 275 | ```c 276 | pool.submit(work); 277 | ``` 278 | 279 | Depending on the type of work, I've distinguished different use-cases. Suppose that the work that we have to do is multiply two numbers. We can do it in many different ways. I've implemented the three most common ways to do it that I can imagine: 280 | * Use-Case #1. Function returns the result 281 | * Use-Case #2. Function updates by ref parameter with the result 282 | * Use-Case #3. Function prints the result 283 | 284 | _Note: This is just to show how the submit function works. Options are not exclusive_ 285 | 286 | ## Use-Case #1 287 | The multiply function with a return looks like this: 288 | 289 | ```c 290 | // Simple function that adds multiplies two numbers and returns the result 291 | int multiply(const int a, const int b) { 292 | const int res = a * b; 293 | return res; 294 | } 295 | ``` 296 | 297 | Then, the submit: 298 | 299 | ```c 300 | // The type of future is given by the return type of the function 301 | std::future future = pool.submit(multiply, 2, 3); 302 | ``` 303 | 304 | We can also use the **auto** keyword for convenience: 305 | 306 | ```c 307 | auto future = pool.submit(multiply, 2, 3); 308 | ``` 309 | 310 | Nice, when the work is finished by the thread pool we know that the future will get updated and we can retrieve the result calling: 311 | ```c 312 | const int result = future.get(); 313 | std::cout << result << std::endl; 314 | ``` 315 | 316 | The get() function of std::future always return the type T of the future. **This type will always be equal to the return type of the function passed to the submit method**. In this case, int. 317 | 318 | ## Use-Case #2 319 | The multiply function has a parameter passed by ref: 320 | 321 | ```c 322 | // Simple function that adds multiplies two numbers and updates the out_res variable passed by ref 323 | void multiply(int& out_res, const int a, const int b) { 324 | out_res = a * b; 325 | } 326 | ``` 327 | 328 | Now, we have to call the submit function with a subtle difference. Because we are using templates and type deduction (universal references), the parameter passed by ref needs to be called using **std::ref(param)** to make sure that we are passing it by ref and not by value. 329 | 330 | ```c 331 | int result = 0; 332 | auto future = pool.submit(multiply, std::ref(result), 2, 3); 333 | // result is 0 334 | future.get(); 335 | // result is 6 336 | std::cout << result << std::endl; 337 | ``` 338 | 339 | In this case, what's the type of future? Well, as I said before, the return type will always be equal to the return type of the function passed to the submit method. Because this function is of type void, the future is **std::future**. Calling future.get() returns void. That's not very useful, but we still need to call .get() to make sure that the work has been done. 340 | 341 | ## Use-Case #3 342 | The last case is the easiest one. Our multiply function simply prints the result: 343 | 344 | We have a simple function without output parameters. For this example I implemented the following multiplication function: 345 | 346 | ```c 347 | // Simple function that adds multiplies two numbers and prints the result 348 | void multiply(const int a, const int b) { 349 | const int result = a * b; 350 | std::cout << result << std::endl; 351 | } 352 | ``` 353 | 354 | Then, we can simply call: 355 | 356 | ```c 357 | auto future = pool.submit(multiply, 2, 3); 358 | future.get(); 359 | ``` 360 | 361 | In this case, we know that as soon as the multiplication is done it will be printed. If we care when this is done, we can wait for it calling future.get(). 362 | 363 | Checkout the [main](https://github.com/mtrebi/thread-pool/blob/master/src/main.cpp) program for a complete example. 364 | 365 | # Future work 366 | 367 | * Make it more reliable and safer (exceptions) 368 | * Find a better way to use it with member functions (thanks to @rajenk) 369 | * Run benchmarks and improve performance if needed 370 | * Evaluate performance and impact of std::function in the heap and try alternatives if necessary. (thanks to @JensMunkHansen) 371 | 372 | # References 373 | 374 | * [MULTI-THREADED PROGRAMMING TERMINOLOGY - 2017](http://www.bogotobogo.com/cplusplus/multithreaded.php): Fast analysis of how a multi-thread system works 375 | 376 | * [Universal References in C++11—Scott Meyers](https://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers): Universal references in C++11 by Scott Meyers 377 | 378 | * [Perfect forwarding and universal references in C++](http://eli.thegreenplace.net/2014/perfect-forwarding-and-universal-references-in-c/): Article about how and when to use perfect forwarding and universal references 379 | 380 | * [C++ documentation](http://www.cplusplus.com/reference/): Thread, conditional variables, mutex and many others... 381 | -------------------------------------------------------------------------------- /affinity.patch: -------------------------------------------------------------------------------- 1 | --- ThreadPool.h Wed May 17 15:01:04 2017 2 | +++ ThreadPool.h Sun Mar 4 04:32:07 2018 3 | @@ -1,5 +1,18 @@ 4 | #pragma once 5 | 6 | +#ifdef AFFINITY 7 | +#if defined __sun__ 8 | +#include 9 | +#include 10 | +#include 11 | +#include /* For sysconf */ 12 | +#elif __linux__ 13 | +#include /* For fprintf */ 14 | +#include 15 | +#endif 16 | +#endif 17 | + 18 | +#include /* For std::size_t */ 19 | #include 20 | #include 21 | #include 22 | @@ -14,10 +27,10 @@ 23 | private: 24 | class ThreadWorker { 25 | private: 26 | - int m_id; 27 | + std::size_t m_id; 28 | ThreadPool * m_pool; 29 | public: 30 | - ThreadWorker(ThreadPool * pool, const int id) 31 | + ThreadWorker(ThreadPool * pool, const std::size_t id) 32 | : m_pool(pool), m_id(id) { 33 | } 34 | 35 | @@ -45,7 +58,7 @@ 36 | std::mutex m_conditional_mutex; 37 | std::condition_variable m_conditional_lock; 38 | public: 39 | - ThreadPool(const int n_threads) 40 | + ThreadPool(const std::size_t n_threads) 41 | : m_threads(std::vector(n_threads)), m_shutdown(false) { 42 | } 43 | 44 | @@ -57,7 +70,44 @@ 45 | 46 | // Inits thread pool 47 | void init() { 48 | - for (int i = 0; i < m_threads.size(); ++i) { 49 | + #if (defined __sun__ || defined __linux__) && defined AFFINITY 50 | + std::size_t v_cpu = 0; 51 | + std::size_t v_cpu_max = std::thread::hardware_concurrency() - 1; 52 | + #endif 53 | + 54 | + #if defined __sun__ && defined AFFINITY 55 | + std::vector v_cpu_id; /* Struct for CPU/core ID */ 56 | + 57 | + processorid_t i, cpuid_max; 58 | + cpuid_max = sysconf(_SC_CPUID_MAX); 59 | + for (i = 0; i <= cpuid_max; i++) { 60 | + if (p_online(i, P_STATUS) != -1) /* Get only online cores ID */ 61 | + v_cpu_id.push_back(i); 62 | + } 63 | + #endif 64 | + 65 | + for (std::size_t i = 0; i < m_threads.size(); ++i) { 66 | + 67 | + #if (defined __sun__ || defined __linux__) && defined AFFINITY 68 | + if (v_cpu > v_cpu_max) { 69 | + v_cpu = 0; 70 | + } 71 | + 72 | + #ifdef __sun__ 73 | + processor_bind(P_LWPID, P_MYID, v_cpu_id[v_cpu], NULL); 74 | + #elif __linux__ 75 | + cpu_set_t mask; 76 | + CPU_ZERO(&mask); 77 | + CPU_SET(v_cpu, &mask); 78 | + pthread_t thread = pthread_self(); 79 | + if (pthread_setaffinity_np(thread, sizeof(cpu_set_t), &mask) != 0) { 80 | + fprintf(stderr, "Error setting thread affinity\n"); 81 | + } 82 | + #endif 83 | + 84 | + ++v_cpu; 85 | + #endif 86 | + 87 | m_threads[i] = std::thread(ThreadWorker(this, i)); 88 | } 89 | } 90 | --- SafeQueue.h Wed May 17 15:01:04 2017 91 | +++ SafeQueue.h Sun Mar 4 04:32:07 2018 92 | @@ -28,7 +28,7 @@ 93 | return m_queue.empty(); 94 | } 95 | 96 | - int size() { 97 | + std::size_t size() { 98 | std::unique_lock lock(m_mutex); 99 | return m_queue.size(); 100 | } 101 | -------------------------------------------------------------------------------- /example/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "../include/ThreadPool.h" 5 | 6 | std::random_device rd; 7 | std::mt19937 mt(rd()); 8 | std::uniform_int_distribution dist(-1000, 1000); 9 | auto rnd = std::bind(dist, mt); 10 | 11 | 12 | void simulate_hard_computation() { 13 | std::this_thread::sleep_for(std::chrono::milliseconds(2000 + rnd())); 14 | } 15 | 16 | // Simple function that adds multiplies two numbers and prints the result 17 | void multiply(const int a, const int b) { 18 | simulate_hard_computation(); 19 | const int res = a * b; 20 | std::cout << a << " * " << b << " = " << res << std::endl; 21 | } 22 | 23 | // Same as before but now we have an output parameter 24 | void multiply_output(int & out, const int a, const int b) { 25 | simulate_hard_computation(); 26 | out = a * b; 27 | std::cout << a << " * " << b << " = " << out << std::endl; 28 | } 29 | 30 | // Same as before but now we have an output parameter 31 | int multiply_return(const int a, const int b) { 32 | simulate_hard_computation(); 33 | const int res = a * b; 34 | std::cout << a << " * " << b << " = " << res << std::endl; 35 | return res; 36 | } 37 | 38 | 39 | int main(int argc, char *argv[]) 40 | { 41 | // Create pool with 3 threads 42 | ThreadPool pool(3); 43 | 44 | // Initialize pool 45 | pool.init(); 46 | 47 | // Submit (partial) multiplication table 48 | for (int i = 1; i < 3; ++i) { 49 | for (int j = 1; j < 10; ++j) { 50 | pool.submit(multiply, i, j); 51 | } 52 | } 53 | 54 | // Submit function with output parameter passed by ref 55 | int output_ref; 56 | auto future1 = pool.submit(multiply_output, std::ref(output_ref), 5, 6); 57 | 58 | // Wait for multiplication output to finish 59 | future1.get(); 60 | std::cout << "Last operation result is equals to " << output_ref << std::endl; 61 | 62 | // Submit function with return parameter 63 | auto future2 = pool.submit(multiply_return, 5, 3); 64 | 65 | // Wait for multiplication output to finish 66 | int res = future2.get(); 67 | std::cout << "Last operation result is equals to " << res << std::endl; 68 | 69 | pool.shutdown(); 70 | 71 | return 0; 72 | } 73 | -------------------------------------------------------------------------------- /include/SafeQueue.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | // Thread safe implementation of a Queue using an std::queue 7 | template 8 | class SafeQueue { 9 | private: 10 | std::queue m_queue; 11 | std::mutex m_mutex; 12 | public: 13 | SafeQueue() { 14 | 15 | } 16 | 17 | SafeQueue(SafeQueue& other) { 18 | //TODO: 19 | } 20 | 21 | ~SafeQueue() { 22 | 23 | } 24 | 25 | 26 | bool empty() { 27 | std::unique_lock lock(m_mutex); 28 | return m_queue.empty(); 29 | } 30 | 31 | int size() { 32 | std::unique_lock lock(m_mutex); 33 | return m_queue.size(); 34 | } 35 | 36 | void enqueue(T& t) { 37 | std::unique_lock lock(m_mutex); 38 | m_queue.push(t); 39 | } 40 | 41 | bool dequeue(T& t) { 42 | std::unique_lock lock(m_mutex); 43 | 44 | if (m_queue.empty()) { 45 | return false; 46 | } 47 | t = std::move(m_queue.front()); 48 | 49 | m_queue.pop(); 50 | return true; 51 | } 52 | }; -------------------------------------------------------------------------------- /include/ThreadPool.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #include "SafeQueue.h" 12 | 13 | class ThreadPool { 14 | private: 15 | class ThreadWorker { 16 | private: 17 | int m_id; 18 | ThreadPool * m_pool; 19 | public: 20 | ThreadWorker(ThreadPool * pool, const int id) 21 | : m_pool(pool), m_id(id) { 22 | } 23 | 24 | void operator()() { 25 | std::function func; 26 | bool dequeued; 27 | while (!m_pool->m_shutdown) { 28 | { 29 | std::unique_lock lock(m_pool->m_conditional_mutex); 30 | if (m_pool->m_queue.empty()) { 31 | m_pool->m_conditional_lock.wait(lock); 32 | } 33 | dequeued = m_pool->m_queue.dequeue(func); 34 | } 35 | if (dequeued) { 36 | func(); 37 | } 38 | } 39 | } 40 | }; 41 | 42 | bool m_shutdown; 43 | SafeQueue> m_queue; 44 | std::vector m_threads; 45 | std::mutex m_conditional_mutex; 46 | std::condition_variable m_conditional_lock; 47 | public: 48 | ThreadPool(const int n_threads) 49 | : m_threads(std::vector(n_threads)), m_shutdown(false) { 50 | } 51 | 52 | ThreadPool(const ThreadPool &) = delete; 53 | ThreadPool(ThreadPool &&) = delete; 54 | 55 | ThreadPool & operator=(const ThreadPool &) = delete; 56 | ThreadPool & operator=(ThreadPool &&) = delete; 57 | 58 | // Inits thread pool 59 | void init() { 60 | for (int i = 0; i < m_threads.size(); ++i) { 61 | m_threads[i] = std::thread(ThreadWorker(this, i)); 62 | } 63 | } 64 | 65 | // Waits until threads finish their current task and shutdowns the pool 66 | void shutdown() { 67 | m_shutdown = true; 68 | m_conditional_lock.notify_all(); 69 | 70 | for (int i = 0; i < m_threads.size(); ++i) { 71 | if(m_threads[i].joinable()) { 72 | m_threads[i].join(); 73 | } 74 | } 75 | } 76 | 77 | // Submit a function to be executed asynchronously by the pool 78 | template 79 | auto submit(F&& f, Args&&... args) -> std::future { 80 | // Create a function with bounded parameters ready to execute 81 | std::function func = std::bind(std::forward(f), std::forward(args)...); 82 | // Encapsulate it into a shared ptr in order to be able to copy construct / assign 83 | auto task_ptr = std::make_shared>(func); 84 | 85 | // Wrap packaged task into void function 86 | std::function wrapper_func = [task_ptr]() { 87 | (*task_ptr)(); 88 | }; 89 | 90 | // Enqueue generic wrapper function 91 | m_queue.enqueue(wrapper_func); 92 | 93 | // Wake up one thread if its waiting 94 | m_conditional_lock.notify_one(); 95 | 96 | // Return future from promise 97 | return task_ptr->get_future(); 98 | } 99 | }; 100 | --------------------------------------------------------------------------------