sleep function vs wait function

I came across another post in this forum:

http://www.cplusplus.com/forum/beginner/15716/

In it, someone makes use of a custom "wait" function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdio.h>
#include <time.h>

void wait ( int seconds )
{
	clock_t endwait;
	endwait = clock () + seconds * CLOCKS_PER_SEC ;
	while (clock() < endwait) {}
}

int main()
{
	for( int i = 0; i < 10; i++ )
	{
		static int foo = 0;
		printf("Waiting ... %d\n", foo);
		foo++;

		wait(1);
	}

	return 0;
}


One forum user said:

"The problem with that delay function is that it spends clock cycles."

Then the user offered the sleep() function as an alternative:

http://pubs.opengroup.org/onlinepubs/009695399/functions/sleep.html

What exactly does the sleep function do differently so it doesn't "spend clock cycles"?
A slightly different version of that is called a spin lock and is used in multi-threaded applications, and it can be faster than other types of locks, but you have to be careful because there can be things that go wrong.
Another useful difference to note between a genuine wait function such as "sleep()" or "Sleep()" and the ad-hoc function you have here, is that with a real wait function the thread will respond to system messages in a timely manner. This was already eluded to, when people mentioned the use of clock cycles and such, but I wanted to emphasis it I guess.

Please remember that timers are a secondary control mechanism; and are of very little use otherwise. You have mutexe's, critical sections, object signal states and a half dozen or more other tools depending on which librar(y\ies) you are using. Even in cases like the first thread that JLBorges linked to where the OP had wanted to accomplish something based on the time of day, custom timers are NOT how you would go about doing this. I know that the contributors were answering the OP's question in the way that it was framed, but Windows Task Scheduler would have been the correct solution for running a daily task.
Topic archived. No new replies allowed.