Limiting the number of threads
As we saw earlier, if there are not enough threads to run several std::async
calls, a std::runtime_system
exception can be thrown and indicate resource exhaustion.
We can implement a simple solution by creating a thread limiter using counting semaphores (std::counting_semaphore
), a multithreading synchronization mechanism explained in Chapter 4.
The idea is to use a std::counting_semaphore
object, setting its initial value to the maximum concurrent tasks that the system allows, which can be retrieved by calling the std::thread::hardware_concurrency()
function, as learned in Chapter 2, and then use that semaphore in the task function to block if the total number of asynchronous tasks exceed the maximum concurrent tasks.
The following snippet implements this idea:
#include <chrono> #include <future> #include <iostream> #include <semaphore> #include <syncstream> #include <vector> #define sync_cout std::osyncstream...