jeudi 23 novembre 2023

Nested use of C++ std::async to create threads, which can delay the exception when there is insufficient resources

I am trying to simulate the exception behavior when the number of threads exceeds the linux limit. I found that when I continuously use std::async(std::launch::async, &func) in a thread, without using try catch, the exception is delayed,program seems getting stucked in the function std::async. However, when using try catch, the exception can be caught in time. In the main function, continuous creation until the exception is thrown does not cause any delay. Can you help me explain this behavior?

int asyncTest(uint16_t i)
{
    std::cout<<"@@@asyncTest = "<<i<<" runstart"<<std::endl;
    cpp_sleepMs(1500*i);
    std::cout<<"@@@asyncTest = "<<i<<" runsend"<<std::endl;
    return i;
}

//running in a thread,when using try catch,it will directly throw exception.
    std::shared_future<int> periodFutTestArray[2000];
//  try {
        for(uint16_t i_cyc=0;i_cyc<2000;i_cyc++)
        {
            std::cout << "@@@asyncTestCreate = "<<i_cyc <<"start"<<std::endl;
            periodFutTestArray[i_cyc] = std::async(std::launch::async, &asyncTest,i_cyc);
            cpp_sleepMs(100);
            std::cout << "@@@asyncTestCreate = "<<i_cyc <<"end"<<std::endl;
        }
//  }catch (const std::exception& e) {
//     std::cerr << "Caught exception: " << e.what() << std::endl;
//  }

std::async stuckedprogram endusing try catchrunning in main func

Aucun commentaire:

Enregistrer un commentaire