I would use the queue and the condition variable and the mutex and start only the requested number of threads, for example, 5 or 20 (and not start 1000).
Each thread blocks a condition variable. When he wakes up, he deactivates the first element, unlocks the queue, works with the element, blocks the queue and checks for the presence of more elements. If the queue is empty, populate the condition variable. If not, open, run, repeat.
While the mutex is locked, it can also check if the user has requested the number of threads. Just check if there is count> max_count, and if so, the thread terminates itself.
At any time, when you have more sites in the queue, just block the mutexes and add them to the queue, and then pass the condition variable. Any threads that are not yet running will wake up and do new work.
Each time the user increases the requested thread counter, just start them, and they will block the queue, conduct a work check and either sleep on the condition variable or get an exit.
Each thread will constantly pull more work out of line or sleep. You do not need more than 5 or 20.
source share