C++ – Sleeping

I am currently using SDL_Delay function in my program, which sleeps for the specified number of milliseconds. But seeing as I’m trying to get rid of SDL, I have to find another cross-platform solution for implementing sleep. So I have to write a replacement function. I’m still figuring out what to call it, but here’s the essentials of a cross-platform sleep.

First of all, do NOT just do a tight while loop. It may appear to pause for that much time, but if you watch the CPU usage for your program, a while-loop like that will use 100% CPU. That is quite unfriendly to people like me with laptops. Not to mention, a 100% utilized CPU can heat up pretty quickly; especially when on a processor like the Pentium 4 (yuck).

So Windows has this handy function inside the all-mighty <Windows.h> file, Sleep(). It takes one argument of how many milliseconds to sleep. This argument can be 0, in which case it yields to another thread for some small amount of time. Or, according to the MSDN documentation, “A value of zero causes the thread to relinquish the remainder of its time slice to any other thread of equal priority that is ready to run. If there are no other threads of equal priority ready to run, the function returns immediately, and the thread continues execution.”

http://msdn.microsoft.com/en-us/library/ms686298(VS.85).aspx

Linux does something pretty different. Their sleep function is inside the include file <unistd.h>, which apparently is a file that contains “standard symbolic constants and types.” The function is usleep, and it takes the parameter of how many microseconds to sleep. That’s right, microseconds. As in, thousandths of milliseconds. So, take the number of milliseconds you want, multiply it by 1000, and give it to this function and your Linux processor will sleep that many milliseconds.

http://opengroup.org/onlinepubs/007908799/xsh/usleep.html

Macs, well, I don’t really know. Nor care. I don’t feel confident enough that I can contort to their differences enough to get my program running on their machines. Meh.

-Ricky

This entry was posted in Code Snippets/Tricks and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s