我的线程可以帮助OS决定何时进行上下文切换吗? [英] Can my thread help the OS decide when to context switch it out?

查看:48
本文介绍了我的线程可以帮助OS决定何时进行上下文切换吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C ++在Linux上开发一个线程应用程序,该应用程序试图做到实时,对心跳进行操作或尽可能接近它.

I am working on a threaded application on Linux in C++ which attempts to be real time, doing an action on a heartbeat, or as close to it as possible.

在实践中,我发现操作系统正在换出线程,并在关闭线程时导致长达十分之一秒的延迟,从而导致心跳不正常.

In practice, I find the OS is swapping out my thread and causing delays of up to a tenth of a second while it is switched out, causing the heartbeat to be irregular.

我的线程是否可以向操作系统提示现在是上下文切换的好时机?我可以在心跳结束后立即拨打此电话,从而将因上下文切换不及时而导致的延迟降到最低.

Is there a way my thread can hint to the OS that now is a good time to context switch it out? I could make this call right after doing a heartbeat, and thus minimize the delay due to an ill timed context switch.

推荐答案

很难说出您所遇到的主要问题是什么,但是最肯定的是不能通过调用 sched_yield来纠正某些问题.() pthread_yield().在Linux中,收益率的唯一明确定义的用途是允许不同的就绪线程在SCHED_FIFO调度策略下在同一CPU上以相同优先级抢占当前受CPU约束的运行线程.在几乎所有情况下,这都是一个糟糕的设计决策.

It is hard to say what the main problem is in your case, but it is most certainly not something that can be corrected with a call to sched_yield() or pthread_yield(). The only well-defined use for yielding, in Linux, is to allow a different ready thread to preempt the currently CPU-bound running thread at the same priority on the same CPU under SCHED_FIFO scheduling policy. Which is a poor design decision in almost all cases.

如果您认真对待Linux中尝试成为实时"的目标,那么首先,您应该使用实时的 sched_setscheduler 设置(SCHED_FIFO或SCHED_RR,首选FIFO).其次,获取针对Linux的完整抢占补丁程序(来自 kernel.org 如果您的发行版不提供该版本,它还使您能够重新安排设备驱动程序线程并在比硬盘或以太网驱动程序线程更高的级别上执行您的线程.第三,请参阅 RTWiki 和其他资源,以获取有关如何设计和设置的更多提示实时应用程序.

If you're serious about your goal of "attempting to be real-time" in Linux, then first of all, you should be using a real-time sched_setscheduler setting (SCHED_FIFO or SCHED_RR, FIFO preferred). Second, get the full preemption patch for Linux (from kernel.org if your distro does not supply one. It will also give you the ability to reschedule device driver threads and to execute your thread higher than, say, hard disk or ethernet driver threads. Third, see RTWiki and other resources for more hints on how to design and set up a real-time application.

这应该足以使您在10毫秒内响应时间,无论任何体面的台式机系统上的系统负载如何.我有一个嵌入式系统,在磁盘/系统负载沉重的情况下,我只能挤出60 us闲置响应和150 us,但这仍然比您描述的要快几个数量级.

This should be enough to get you under 10 microseconds response time, regardless of system load on any decent desktop system. I have an embedded system where I only squeeze out 60 us response idle and 150 us under heavy disk/system load, but it's still orders of magnitude faster than what you're describing.

这篇关于我的线程可以帮助OS决定何时进行上下文切换吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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