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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
They’re not equivalent.
std::this_thread::yieldshould map tosched_yieldandSwitchToThread, respectively. I’m saying “should” because if depend on the implementation, of course.These give up the current timeslice and reschedule.
SwitchToThreadonly 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_yieldmoves 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 haveSleep(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).