Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yield between different processes

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?

like image 960
André Puel Avatar asked Sep 22 '11 22:09

André Puel


2 Answers

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

like image 91
msh Avatar answered Sep 21 '22 14:09

msh


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.

like image 34
fbafelipe Avatar answered Sep 21 '22 14:09

fbafelipe