1

Not to familiar with threading development so please forgive if this is obvious. I am using MS VS 2013, Cx11. Question pertains to asynchronous tasks and how many threads does a call to async - or later future.get(), actually spawns. If I have a self contained function:

int PewPewPew(int k)
{
    std::this_thread::sleep_for(std::chrono::seconds(1));
    return k;
}

That gets called a LARGE_MAX times:

vector<future<int>> futures;

int LARGE_MAX = 1000000;
for (int i = 0; i < LARGE_MAX; ++i)
    futures.push_back(async(PewPewPew, i));

int total = 0;
for (auto &f : futures)
    total += f.get();
cout << "Total: " << total << endl;

Is there some kind of "smart" thread management that would not over spawn the number of threads running this code? I am assuming on most desktops LARGE_MAX concurent threads would not be efficient?

Thanks!

Update: I guess to clarify (from comments): I know there are different ways using std:: to accomplish the above task. But as far as i understand, the function PewPewPew() constitutes a task and so can be used as above. So my question then is would the code above lead to "inefficient threading" if LARGE_MAX is larger then the current systems optimal thread number.

Nicko Po
  • 727
  • 5
  • 21
  • `std::async` may not spawn any threads at all. And the number of concurrent processes/threads before effectiveness goes down depends very much on the processor used, and also the operating system (and even which version of the operating system may be a factor). So in short there's really no one right answer for this question. – Some programmer dude Nov 21 '14 at 19:59
  • You can use a thread pool with a work queue: http://stackoverflow.com/a/22570554/85371 – sehe Nov 21 '14 at 20:00
  • Related: http://stackoverflow.com/q/15666443 – dyp Nov 21 '14 at 22:03

0 Answers0