YuHuanTin
YuHuanTin

Reputation: 1

The function called by std::async is not executed immediately?

#include <iostream>
#include <future>
auto gClock = clock();

char threadPool(char c) {
    std::cout << "enter thread :" << c << " cost time:" << clock() - gClock << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(2));
    for (int i = 0; i < 10; i++)
        std::cout << c;
    std::cout << std::endl;
    return c;
}
void fnTestAsync(){
    auto begin = clock();
    std::future<char> futures[10];
    for (int i = 0; i < 10; ++i){
        futures[i] = std::async(std::launch::async,threadPool, 'a' + i);
    }
    for (int i = 0; i < 10; ++i){
        std::cout << futures[i].get() << " back ,cost time: " << clock() - begin << std::endl;
    }

    std::cout << "fnTestAsync: " << clock() - begin << std::endl;
}
int main(){
    std::thread testAsync(fnTestAsync);
    testAsync.detach();
    std::this_thread::sleep_for(std::chrono::seconds(10));
    return 0;
}

run result

I'm trying to get these 10 threads to execute together and all return immediately after a two second delay, but I output the time spent and find that it takes about 2900ms, much larger than the 2000ms I expected.

What is the cause of this increase? How should he fix it?

Upvotes: 0

Views: 110

Answers (0)

Related Questions