不同工艺间的良率
我有两个 C++ 代码,一个名为 a,另一个名为 b。我在 64 位 Linux 上运行,使用 Boost 线程库。
a 代码创建 5 个线程,这些线程处于非结束循环中执行某些操作。 b 代码创建 5 个线程,这些线程停留在调用 Yield() 的无结束循环中。
我在四核机器上...当 a 单独调用 a 代码时,它几乎获得了 400% 的 CPU 使用率。当 a 单独调用 b 代码时,它几乎获得了 400% 的 CPU 使用率。我已经预料到了。
但当两者一起运行时,我预计 b 代码几乎不使用 CPU,而 a 使用 400%。但实际上两者都使用相同的 CPU 切片,几乎 200%。
我的问题是,yield() 在不同进程之间不起作用吗?有没有办法让它按照我预期的方式工作?
I have two C++ codes one called a and one called b. I am running in in a 64 bits Linux, using the Boost threading library.
The a code creates 5 threads which stay in a non-ending loop doing some operation.
The b code creates 5 threads which stay in a non-ending loop invoking yield().
I am on a quadcore machine... When a invoke the a code alone, it gets almost 400% of the CPU usage. When a invoke the b code alone, it gets almost 400% of the CPU usage. I already expected it.
But when running both together, I was expecting that the b code used almost nothing of CPU and a use the 400%. But actually both are using equals slice of the CPU, almost 200%.
My question is, doesn't yield() works between different process? Is there a way to make it work the way I expected?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因此,您有 4 个内核运行属于 A 的 4 个线程。队列中有 6 个线程 - 1 个 A 和 5 个 B。其中一个正在运行的 A 线程耗尽其时间片并返回到队列。调度程序从队列中选择下一个可运行的线程。该踏板属于 B 的概率是多少? 5/6。好的,这个线程启动了,它调用 sched_yield() 并返回到队列中。下一个线程又是 B 线程的概率是多少?又是5/6!
进程B一次又一次地获得CPU时间,并且还迫使内核进行昂贵的上下文切换。
sched_yield 适用于一种特定情况 - 当一个线程使另一个线程可运行时(例如,解锁互斥锁)。如果你想让 B 在 A 正在处理重要事情时等待 - 使用某种同步机制,可以让 B 进入睡眠状态,直到 A 将其唤醒
So you have 4 cores running 4 threads that belong to A. There are 6 threads in the queue - 1 A and 5 B. One of running A threads exhausts its timeslice and returns to the queue. The scheduler chooses the next runnable thread from the queue. What is the probability that this tread belongs to B? 5/6. Ok, this thread is started, it calls sched_yield() and returns back to the queue. What is the probability that the next thread will be a B thread again? 5/6 again!
Process B gets CPU time again and again, and also forces the kernel to do expensive context switches.
sched_yield is intended for one particular case - when one thread makes another thread runnable (for example, unlocks a mutex). If you want to make B wait while A is working on something important - use some synchronization mechanism that can put B to sleep until A wakes it up
Linux 使用动态线程优先级。你用nice设置的静态优先级只是为了限制动态优先级。
当一个线程使用他的整个时间片时,内核将降低它的优先级,而当一个线程不使用他的整个时间片(通过执行 IO、调用 wait/yield 等)时,内核将提高它的优先级。
所以我的猜测是进程b线程具有更高的优先级,因此它们执行得更频繁。
Linux uses dynamic thread priority. The static priority you set with nice is just to limit the dynamic priority.
When a thread use his whole timeslice, the kernel will lower it's priority and when a thread do not use his whole timeslice (by doing IO, calling wait/yield, etc) the kernel will increase it's priority.
So my guess is that process b threads have higher priority, so they execute more often.