How can I tell if a thread is being starved of cpu?

I have a thread that naturally has a blocking function. Let’s say it is a message receive just to have an example. It should normally sit at that blocking function except when a message arrives, at which point it executes some code and goes back to waiting on for another message.

What if this thread was being starved of cpu? It would block, then a message would arrive that puts it in the ready state, then time would pass, then it would finally process that message. By the time it blocks again, there might already be another message watiing. If this happened regularly, then it would indicate that it is being starved of cpu, right?

My question is…how would I detect that situation? It doesn’t appear there is anything in the Thread class to say “what percentage of time am I spending in the ready state” - I’m sure that would be hard to implement. Ideas? Thanks.

This is going to be extremely platform dependant as we are talking about scheduler behaviour here.
As far as the Thread is concerned, it does not “know” that it was bumped off the cpu or not.

On linux you can use trace-cmd to record sched_wakeup and sched_switch events, and then use kernelshark to visualise. This will show you exactly when you thread was put in the RUN state, when it actually started running on the CPU, and when it gets bumped off the CPU because some other task had some work to do.

I’m not sure which tools exist on windows or mac to do that, but you have a lot less control over those schedulers anyways, so it could help you understand what happens but may not help solving the issue.

Thanks for the reply. This thread is in a plugin that runs on mac/windows. I guess that clarifies it - even if I could determine the thread is starved, I don’t have much control. I do hope that Thread::setPriority will help, because that is the only path forward I think. I will assume my thread under suspicion is getting starved of cpu, and instead of leaving it at the default priority of 5, I will set it to 8 (still needs to be below real time audio thread prio which is 9).