[phobos] Sleep(0) vs Sleep(1) for yield

SK sk at metrokings.com
Sun Sep 5 09:17:00 PDT 2010


Hello,
Core.thread.yield call has a performance hobbling work-around for
scheduler problems in Windws XP and earlier:

    /**
     * Forces a context switch to occur away from the calling thread.
     */
    static void yield()
    {
        version( Windows )
        {
            // NOTE: Sleep(1) is necessary because Sleep(0) does not give
            //       lower priority threads any timeslice, so looping on
            //       Sleep(0) could be resource-intensive in some cases.
            Sleep( 1 );
        }
        else version( Posix )
        {
            sched_yield();
        }
    }


Microsoft fortunately fixed the problem for new versions of Windows,
starting with Windows Server 2003 as described here:
http://msdn.microsoft.com/en-us/library/ms686298%28VS.85%29.aspx

On Windows 7:
Sleep(1), the workaround, allows only 1000 thread yields per second
per core, which is agonizingly slow.
Sleep(0) allows 4.7 Million yields per second per core on my 2.6GHz machine.

Any objection to changing to Sleep(0) for Windows 2003 and above?
What definition is suitable for use in version() to make this distinction?

Regards,
-steve


More information about the phobos mailing list