1

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).

3
  • 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? Commented 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. Commented 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. Commented Dec 30, 2016 at 19:30

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.