close
Namespaces
Variants

Talk:cpp/thread/sleep for

From cppreference.com

Does the sleep get terminated early by SIGALRM like nanosleep() does?205.175.226.97 12:07, 3 October 2017 (PDT)

no. No such termination condition is specified and implementations just go back to nanosleep if it gets interrupted: libcxx, libstdc++. --Cubbi (talk) 13:00, 3 October 2017 (PDT)

(after maybe a thousand helpful lookups at this site, I think I have feedback)

The Example on this page uses the "2000ms" notation and so I think it requires:

   using namespace std::chrono_literals;

Definitely so when I tested it in c++17.

--Cwr (talk) 16:54, 6 February 2023 (PST)

 Done. Certainly so.--Space Mission (talk) 03:06, 7 February 2023 (PST)

Thanks, but I do not see the edit.

--Cwr (talk) 07:27, 8 February 2023 (PST)

No edit was required, refer to line 7 of the example --Ybab321 (talk) 08:10, 8 February 2023 (PST)

This entry is labelled C++11 onwards but the example requires C++20. This confused me. If someone who understands this better than I do could provide a C++11 compliant example, that would be kind. Lin Manfu (talk) 14:06, 1 May 2023 (PDT)

 Sure:
#include <iostream>
#include <chrono>
#include <thread>
 
int main()
{
//  using namespace std::chrono_literals; // C++14
 
    std::cout << "Hello waiter\n" << std::flush;
 
    const auto start = std::chrono::high_resolution_clock::now();
//  std::this_thread::sleep_for(2000ms); // C++14
    std::this_thread::sleep_for(std::chrono::milliseconds(2000));
    const auto end = std::chrono::high_resolution_clock::now();
    const std::chrono::duration<double, std::milli> elapsed = end - start;
//  std::cout << "Waited " << elapsed << '\n'; // C++20
    std::cout << "Waited " << elapsed.count() << '\n';
}

Possible output:

Hello waiter
Waited 2000.15
--Space Mission (talk) 14:18, 1 May 2023 (PDT)