Richard Carter

Computer Science & Game Development Student at North Carolina State University

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

Share this article:
  • Print
  • RSS
  • email
  • Digg
  • del.icio.us
  • Facebook
  • Twitter
  • Live
  • StumbleUpon

Add A Comment

Sorry for the mess! I recently got hacked and lost my previous theme, so I'm working on reconstructing that. In the meantime, this theme is messy/broken but at least you can read my posts. Sorry!!


Hi, I'm Richard Carter! I use this blog to document particularly difficult-to-solve computer problems. My posts are written for clarity and keywords for search engines to pick up on, so that the next person that runs into the same problem will easily find my solution here and have an easier time than I had! I'm forging a path through the brush, so to speak. So if you came here by search engine, I guess it worked! Enjoy the solution to your problem.