Question

anI used a C++ framework, where yield at the end of every loop cycle was mandatory. Now that I'm starting with C# and C++/CLI, I came across the yield function as well. I'm creating an event loop and was wondering if the use of yield is necessary. I'm not creating a game, where frame rate is important, I'm going for maximum performance (speed).

function main
{
    initialize
    loop(!quit){
        update input
        update application
        render
        yield
    }
    terminate
}

Isn't a platform capable of dividing the running time properly between different applications and should I use yield because of that?

If yes, for how long should I do this and isn't it better to use thread sleep, so threads with lower priority get some extra time as well?

Answers about other languages the .NET are also appreciated. I'm just curious if the general purpose of yield is really necessary.

Thanks

Was it helpful?

Solution

As far as I understand the yield to use here is the same as sleep(0.00...01) would be. It tells the scheduler that you do not need to do more work at the moment.

The platform is capable of dividing the time, but it cannot know (without you telling it), when it is the best to interrupt a thread.

So without yielding the process/thread, the scheduler might make your thread go through 29 times the loop immidiately, which is redundant, since there might be no new input. And then you will not get another round for a whole second. It is better to yield instead of doing redundant work, so you can get back to work that much sooner when it will matter.

The other reason is that the scheduler has good chances of pausing your loop when you are in the middle, which means rendering will be late. Yielding at the end means that, if the scheduler intends more time for your thread/process than what one looping takes on average, then you are less likely to get the thread/process paused in the middle of the loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top