放弃C ++中当前线程的时间片 [英] Giving up the time slice for current thread in C++

查看:263
本文介绍了放弃C ++中当前线程的时间片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下语句是否等同放弃当前线程的时间片?

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


推荐答案

std :: this_thread :: yield 应映射到 sched_yield SwitchToThread 。我说应该,因为如果依赖于实现,当然。

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.

这些放弃当前的时间片和重新安排。 SwitchToThread 仅仅尊重当前CPU上的线程,但是没有关于调用线程在就绪队列中的位置的统计,除了如果在同一个CPU上有另一个线程就绪,首先运行

sched_yield 将线程移动到就绪队列的末尾并重新调度。

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)在Windows下大致相同,除了它更不可靠所有不可能有 Sleep(0)在50-100ms之后返回),它不尊重CPU边界,即在另一个CPU上运行的线程可能会移动。

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)即在Linux / BSD / POSIX /无论什么)真正做你要求的,它睡觉为零时间,即不是所有。它只是一个无用的上下文切换,立即返回(我们实际上已经发生了一次,当你假设它只是像Windows下工作时令人惊讶)。

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

这篇关于放弃C ++中当前线程的时间片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆