Is there any way to set maximum amount of threads that can be created by use async function (from future)? I prefer to use async/future.get because it can be translate to sync/spawn multitasking model, which is common in textbooks on Alghoritms(ie. Cormen). I want to be able to obtain T[p] (time to finish program using p processors/ threads).
-
You could put all your calls to async in a method of a class that would refuse to do anything if the number of calls to the member function is higher than some limit that you could specify when constructing an instance of the class. What would you want your programme to do if it reached or exceeded the limit?James Mitchell– James Mitchell2016-12-30 17:42:50 +00:00Commented Dec 30, 2016 at 17:42
-
Quick and dirty solution: initialize a semaphore to the number of threads you want to be able to proceed at once. Make your thread procedures wait on that semaphore. This doesn’t free you from the overhead of thread creation, but at least any extra threads will just spin quietly.Davislor– Davislor2016-12-30 19:25:02 +00:00Commented Dec 30, 2016 at 19:25
-
Alternatively: have an atomic (priority) queue and have the worker threads in your pool get their next task from the queue, but you already said you’d rather do sync/spawn.Davislor– Davislor2016-12-30 19:30:47 +00:00Commented Dec 30, 2016 at 19:30
Add a comment
|
1 Answer
Unfortunately no. std::async is rather notoriously limited in the control it provides you over how threads are created.
You might consider using a boost thread pool instead. This is (somewhat counter intuitively) part of boost asio, and uses an io_service object, even when/if you're not actually using it for I/O.
With this it's fairly easy to control the number of threads used, including using only one.
Of course you could build your own thread pool class from the standard components. Certainly possible, but not an entirely trivial task.