Giving up the time slice for current thread in C++


This question already has an answer here:


They're not equivalent. std::this_thread::yield should map to sched_yield and SwitchToThread, respectively. I'm saying "should" because if depend on the implementation, of course.

These give up the current timeslice and reschedule. SwitchToThread only respects threads on the current CPU but makes no statment about the calling thread's position in the ready queue other than if there is another thread ready on the same CPU, that one runs first. sched_yield moves the thread to the end of the ready queue and reschedules.

Sleep(0) does more or less the same under Windows, except it is more unreliable (it's not at all impossible to have Sleep(0) return after 50-100ms!) and it does not respect CPU boundaries, i.e. a thread that would run on another CPU might get moved. No issue on a "normal household" dualcore, big issue on a NUMA server.

nanosleep(timespec_with_zero_ns) (i.e. under Linux/BSD/POSIX/whatever) really does what you ask for, it sleeps for zero time, i.e. not at all. It's just a useless context switch that returns immediately (we've actually had this happen once, it's surprising when you assume it just works like under Windows).

Sleep for: 'Blocks the execution of the current thread for specified sleep_duration. May block for longer than sleep_duration.'

It really depend of the implementation, and the operating system.

std::this_thread::yield() is the standard way (the non-specific-implementation dependent) to give up the time slice.

Need Your Help

I need to count values in one column in Excel when they meet criteria in another column

database excel function spreadsheet worksheet

I'm trying to create a statistics report that gets automatically updated as data is put into a corresponding worksheet. So this being said, there's no telling how much data will be put into the da...