Sleep() vs sleep_for()

user8554358 picture user8554358 · Mar 2, 2018 · Viewed 10.3k times · Source

Can someone explain the difference in behavior between these two ways of stopping a thread and then continue it again?.

Sleep(); //from Win32

std::this_thread::sleep_for();

I remark in terms of multithreading behavior not in systems compatibility.

Answer

Mikaela Szekely picture Mikaela Szekely · Mar 2, 2018

The difference is that sleep_for() is defined by the C++11 standard, and Sleep() is defined by the Windows API. If you use sleep_for(), it is quite likely, though not certain, that the compiler will generate code that calls Sleep() when compiling for Windows. However, since it is a C++11 standard function, that means that any compiler (correctly) implementing the C++11 standard will have some way to generate code for the functionality described by the function for any platforms it supports.

The other major difference is that sleep_for() takes an std::chrono::duration as a parameter instead of an integer in milliseconds. This allows you to more easily and more precisely specify the time for which you want the thread to sleep. It also moves some documentation information into the type system.

You wanted to know the implications of sleep_for() versus Sleep() for multithreading, and all I can say is that sleep_for() has the implications defined in the C++11 standard, and Sleep(), has the implications defined in the Windows API. And if you check the reference, each one talks about its respective thread type. So if you're using C++11 threads, use sleep_for(). If you're using Win32 threads directly, use Sleep(). Sleep() does not have any notion of C++11 threads, and so does not have clearly defined behavior. Likewise, sleep_for() does not have a notion of Windows API threads, and so does not have clearly defined behavior there either. The documentation for each function specifies its interactions with its respective threads. Don't mix standards.