Managing threads and sharing data
As discussed previously, executing threads involves pausing and resuming some of them if the number of threads exceeds the number of parallel running threads supported by the hardware. Besides that, creating a thread also has an overhead. One of the suggested practices to deal with having many threads in a project is using thread pools.
The idea of a thread pool lies in the concept of caching. We create and keep threads in a container to be used later. This container is called a pool. For example, the following vector represents a simple thread pool:
#include <thread>#include <vector> std::vector<std::thread> pool;
Whenever we need a new thread, instead of declaring the corresponding std::thread
object, we use one already created in the pool. When we are done with the thread, we can push it back to the vector to use it later if necessary. This saves us some time when we’re working with 10 or more threads. A proper...