1
bool tf()
{
    sleep(5000);
    return true;
}

int main()
{
    std::future<bool> bb = std::async(std::launch::async, tf);
    bool b = false;
    while(1)
    {   
        if(b == true) break;

        b = bb.get();
    }   

    return 0;
}

why don't work? I intended to terminate program after 5 seconds. However, the program is freezing.

user3416447
  • 119
  • 1
  • 2
  • 9

1 Answers1

0

There is a much better alternative to the direct use of invoking a global sleep. Use the <chrono> header and the string literals it provides together with std::this_thread::sleep_for. This is less error prone, e.g.

#include <chrono>

// Bring the literals into the scope:
using namespace std::chrono_literals;

bool tf()
{
   std::this_thread::sleep_for(5s);
   //                          ^^ Awesome! How readable is this?!

   return true;
}

Together with the rest of the snippet you posted, this should work as intended.

T.C.
  • 133,968
  • 17
  • 288
  • 421
lubgr
  • 37,368
  • 3
  • 66
  • 117