Boost logo

Boost Users :

From: simonwlb (conic_at_[hidden])
Date: 2002-03-07 20:01:02


I'm using thread::yield() in my multi-threaded cross-platform
application to avoid "CPU burn".

This is because I have threads that are in an infinte loop in order
to do some polling. There are no mutexes to wait on in the loop.

void X::threadFunction()
{
  for(;;)
  {
    if( m_x->isReady() )
      doSomething();
    .
    .
    .
    boost::thread::yield();
  }
}

If the answer is "you should almost never poll like that - try to use
mutexes etc. as much as possible" please say so (I'm a newbie to
threads)!

In any case, if I choose to have a thread in an infinite loop anyway,
I have three options (assuming I have no mutexes available to me):
1. Don't yield or Sleep at all.
2. Sleep for a while - say for example, 10 ms.
3. Yield.

Option 1 is clearly wrong. The CPU usage will go to 100% and the
whole machine may slow down to an unusable speed.

Option 2 works well in my emperical tests. The thread loop executes
plenty fast enough and my Windows CPU meter shows virtually 0% CPU
usage. 10ms is a bit of an arbitrary figure though - My code needs
to work on a variety of software and hardware platforms, so the ideal
number is hard or impossible to know.

Option 3 also works well in my emperical tests and seems like the
neat solution (no arbitrary waiting period). My application and the
system as a whole both run smoothly and fast. The only irksome thing
is that the CPU meter shows 100% usage. That's a bit alarming for me
and the users of my software.

My questions:
1. Should thread loops without logical wait conditions be avoided as
much as possible? Is that the problem?

2. Should I just yield() or should I pause for a time period?

3. How do you select a time period to wait?

Simon Bailey


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net