Indeed, if you use proper
Sleep
method, you will yield the CPU to other threads. You did not show what is your
Sleep
, exactly. I hope, this is a right one:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms686298%28v=vs.85%29.aspx[
^].
Indeed, if a thread calls this function, it is switched off by the OS and put in a special wait state; and it will not be scheduled back to execution effectively wasting zero CPU time until it is waken up; and the wake-up mechanism does not spend any CPU time as it is embedded in the thread scheduler, and a hardware interrupt is involved, in case of timing. The thread can be waken up by different causes. First of all, it will be waken up by the expiration of the sleep time, but be aware that this time can be a little longer then specified, this method is not designed for perfect accuracy, and the OS is not a real-time one. Other methods allows other threads to wake up this thread; such as setting a event object if your waiting thread is waiting at one or more of them.
Now, I don't think it makes any sense in your particular case, if I understand the purpose of your code, of course. It looks like you are trying to develop some kind of UI based on events. Such mechanism do not really require wait. A regular Windows UI already wastes zero CPU time if a user don't activate it or don't press keyboard keys or operate mouse over the activated application window (this includes console window). This is done through
GetMessage
/
DispatchMessage
cycle. When a message queue is exhausted, all previously sent messages are processes and the user does not send input, the application wastes zero CPU time (if there are no other thread which may or may not use it despite of the user inactivity).
This works for console applications as well; for example, you can simply call
std::cin.get();
and the application will waste zero CPU time until the input is sent. [EDIT] (Here, "cin" means "console input stream".) [END EDIT]
[EDIT]
For example:
char c, str[256];
cout << "Enter the name of an existing text file: ";
cin.get (str,256);
cout << "Enter some character: ";
c = cin.get();
—SA