Are C++ async tasks executed in parallel on different threads on most common std libs and systems?

Viewed 97

C++ <futures> is the asynchronous tasks standard library. A good use of async operations are IO which need to wait on external operations. However what about parallelizing CPU intensive operations?

AFAIK the standard doesn't guarantee that tasks will be run in parallel on other threads (e.g. std::async "runs a function asynchronously (potentially in a new thread)"). But I am interested in practice on modern desktops. I.e. GCC, clang, MSVC (with their respective implementations of the standard library) on x64. In practice will async tasks be parallelized across the available threads on these systems?


Example:

I am not interested in this algorithm specifically, it's just a simple example of embarrassing parallel CPU intensive algorithm:

Can we use async to brute force count the number of floats in an interval or do we need to use manual threads if we want parallelism?


unsigned long long count_floats(float from, float to)
{
    unsigned long long count = 0;
    for (float f = from; f < to; f = std::nextafter(f, std::numeric_limits<float>::infinity()))
    {
        ++count;
    }
    return count;
}

int main()
{
    unsigned long long count = 0;
    std::vector<std::future<unsigned long long>> counters;

    for (float f = -100.0f; f < 99.0f; f += 1.0f)
    {
        counters.push_back(std::async(count_floats, f, f + 0.1f));
    }

    unsigned long long total_floats = 0;
    for (auto& counter : counters)
    {
        total_floats += counter.get();
    }

    std::cout.imbue(std::locale(""));   
    std::cout << "total: " << total_floats << std::endl;
}
1 Answers

According to this post, it seems that in clang/LLVM, gcc, and msvc a thread is always used.

For GCC and LLVM a thread is simply spawned. However, msvc differs in that it reuses a thread from a thread-pool.

Related