RE: Question about sched_yield()

David Schwartz (davids@webmaster.com)
Tue, 18 Jun 2002 15:03:31 -0700


> 3. A CPU hog at best when running on an SMP boxes: the spinning
>thread gobbles up a whole 100% of a CPU.

For the few hundred cycles some other thread holds the lock.

>"Smart" spinlocks basically try and do it this way:
>
> int spinLoops= GetNumberOfProcsICanRunOn() > 1 ? someBigNumber : 1;
> while(1)
> {
> int n= spinLoops;
> while(n--) tryAndGetTheSpinLock();
> if(gotIt) break;
> sched_yield();
> }
>
>These seem to have all the qualities I want:

Almost.

>2. On an SMP box, the thread will bang on the spinlock a large
>number of times, hoping to get it before it gets taskswitched away.
>If it does, great: no time lost.
>If it doesn't, we're out of luck, yield the CPU and try again next time.

You should limit how many times you spin in this loop. If it gets to be too
many, you should block.

You can either block by sleeping for a few milliseconds. If you don't like
the idea that one thread will release the lock and the other will waste time
sleeping, then associate a kernel lock with the spinlock when a thread gives
up waiting, have your unlock function check for an associated kernel lock and
if there is one, unlock it.

DS

-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@vger.kernel.org
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/