wait of condition_variable in C++ will consume CPU resource?

Viewed 420

I ran the following snip of code in both Linux and Windows to check whether cv.wait() will occupy the CPU during the wait period.

#include <mutex>              // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable, std::cv_status

std::condition_variable cv;

int main()
{
    std::mutex mtx;
    std::unique_lock<std::mutex> lck(mtx);
    cv.wait_for(lck, std::chrono::milliseconds(100000), []() {return false; });
    return 0;
}

The result shows a big difference.

  • In Linux, I check it with htop, the usage of this process is 100%.
  • In Windows, I check it with task manager, the usage is prone to 0.

By the way, if I start a new thread and put the above code in that, the usage in Linux is almost 0.

It puzzles me a lot, my question are:

  1. whether the cv.wait will give up CPU resource which is similar with sleep?
  2. why it differs a lot in multi-thread in Linux?
0 Answers
Related