samedi 27 novembre 2021

How to achieve that a thread in multithreading ends first, and the main thread continues to execute

I try to implement a function: the primary thread creates multiple sub-threads and blocks the primary thread, and wakes up the primary thread to continue execution when any of the sub-threads ends. The following code is my attempt to use std::future in C++11:

std::pair<size_t, size_t> fun(size_t i, size_t j)
{
    std::this_thread::sleep_for(std::chrono::seconds(i * j));
    return { i, j };
}

int main()
{
    std::shared_future<std::pair<size_t, size_t>> ret;
    std::pair<size_t, size_t> temp;

    ret = std::async(fun, 10, 9);
    ret = std::async(fun, 5, 4);
    ret = std::async(fun, 2, 1);
    temp = ret.get();
    std::cout << temp.first << "\t" << temp.second << "\n";

    return 0;
}

For the result, I hope the program will directly output "2 1" after (2 * 1) seconds and end the primary thread, but in my attempt, the program needs to wait for the first sub-thread to sleep for (10 * 9) seconds before outputting "2 1" and end the primary thread.

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire