C++11 Thread waiting behaviour: std::this_thread::yield() vs. std::this_thread::sleep_for( std::chrono::milliseconds(1) )

前端 未结 4 418
小蘑菇
小蘑菇 2020-12-08 06:46

I was told when writing Microsoft specific C++ code that writing Sleep(1) is much better than Sleep(0) for spinlocking, due to the fact that Sleep(0)

4条回答
  •  感动是毒
    2020-12-08 07:27

    if you are interested in cpu load while using yield - it's very bad, except one case-(only your application is running, and you are aware that it will basically eat all your resources)

    here is more explanation:

    • running yield in loop will ensure that cpu will release execution of thread, still, if system try to come back to thread it will just repeat yield operation. This can make thread use full 100% load of cpu core.
    • running sleep() or sleep_for() is also a mistake, this will block thread execution but you will have something like wait time on cpu. Don't be mistaken, this IS working cpu but on lowest possible priority. While somehow working for simple usage examples ( fully loaded cpu on sleep() is half that bad as fully loaded working processor ), if you want to ensure application responsibility, you would like something like third example:
    • combining! :

      std::chrono::milliseconds duration(1);
      while (true)
         {
            if(!mutex.try_lock())
            {
                 std::this_thread::yield();
                 std::this_thread::sleep_for(duration);
                 continue;
            }
            return;
         }
      

    something like this will ensure, cpu will yield as fast as this operation will be executed, and also sleep_for() will ensure that cpu will wait some time before even trying to execute next iteration. This time can be of course dynamicaly (or staticaly) adjusted to suits your needs

    cheers :)

提交回复
热议问题