C11: sleep for vs yield

While reviewing the code, std::this_thread::yield() suddenly popped into my view, a syntax sugar from C11 that I’d used quite a bit, but hadn’t noticed before.

I didn’t consult the manual; first, I thought it had something to do with asynchronous operations – the word was used in the coroutine implementation of the Boost library. Clearly, it wasn’t related to coroutines; it’s about controlling logic within a regular thread.

Documentation

yield

The accuracy of this function depends on the implementation, particularly the OS scheduler mechanism and system state used. For example, the First-Come, First-Served (FCFS) real-time scheduler (Linux’s SCHED_FIFO) will suspend the current thread and place it at the end of the queue for other threads with the same priority that are ready to run (and has no effect if there are no other threads with the same priority).

sleep_for

Blocks the current thread’s execution for at least the specified sleep_duration. This function may block longer than sleep_duration due to scheduling or resource contention delays. The standard library recommends measuring durations using a monotonic clock. If implementing with system time instead, waiting times may be sensitive to clock adjustments.

Analysis

Both functions are designed to release the current thread and its associated resources, with the actual effect depending on the platform. I’m still a bit unclear at this point, so let’s run the code to see the execution results.

ThinkPad laptop (Visual Studio Community 2022), Tencent Cloud S2 Standard Server (gcc8.5)

Analysis

Execution Platform Function First/us Second/us Third/us

Analysis

Execution Platform Function First Time / us Second Time / us Third Time / us

Analysis

Execution Platform Function First/us Second/us Third/us

Analysis

Execution Platform Function First/us Second/us Third/us

Analysis

From the results, it’s clear that due to differences in operating system implementations, the stability of high-precision sleep varies greatly. If you want high-precision sleep, using yield is more appropriate.

When the time precision is increased to ms, the difference between the two methods is not significant.

References

Licensed under CC BY-NC-SA 4.0
Last updated on Jun 02, 2025 20:54
A financial IT programmer's tinkering and daily life musings
Built with Hugo
Theme Stack designed by Jimmy