Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Giving up the time slice for current thread in C++ [duplicate]

Are the following statements equivalent ways for giving up the time slice for the current thread?

std::this_thread::sleep_for(std::chrono::milliseconds(0));
std::this_thread::yield;
Sleep(0);  // On windows
like image 397
Phillip Ngan Avatar asked Jun 15 '12 10:06

Phillip Ngan


1 Answers

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).

like image 138
Damon Avatar answered Nov 15 '22 00:11

Damon