0

I have a thread which is running in a loop and executing tasks.

outTask::Task* task;
while (!m_out_stop) {
    println("abc");
    while (m_outQueue.pop(task)) {
        println("123");
        task->execute();
    }
}

How can I make this less CPU intensive? I could make the thread sleep between each task, but that would cause a delay, and is therefore not an ideal solution.

Ps. Print statements are for debugging purposes.

KaareZ
  • 615
  • 2
  • 10
  • 22
  • with boost you could use boost::this_thread::yield(). withh c++11 you could use std::this_thread::yield() – user5976242 Mar 23 '16 at 17:11
  • @user5976242 At least on windows, `yield` does not reduce the CPU usage. if you yield, but the scheduler has no other threads to schedule on that cpu, it will simply reschedule your thread immediately, thus throttling the cpu. – sbabbi Mar 23 '16 at 17:41
  • @sbabbi You are correct. I guess I just don't understand the problem. If no other thread is ready to run then I want to use maximum CPU to complete my task (I don't care if it is CPU intensive). However, if my task is hogging the CPU and preventing other threads from responding /operating smoothly then I would want to yield. – user5976242 Mar 23 '16 at 17:52
  • Am I right that the most CPU load happens when the queue is empty and the loop just keeps checking `m_out_stop`? – Anton Savin Mar 23 '16 at 22:36

1 Answers1

0

If you are working in windows could use SetThreadPriority:

outTask::Task* task;
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);
while (!m_out_stop) {
.....

It makes run slowest your working thread, but not stop it

Ing. Gerardo Sánchez
  • 1,607
  • 15
  • 14