C programming language provides sleep()
function in order to wait for a current thread for a specified time. slepp()
function will sleep given thread specified time for the current executable. Of course, the CPU and other processes will run without a problem.
Include unistd.h Library In Linux
sleep()
function is provided by unistd.h
library which is a short cut of Unix standard library. We can include this library as below.
#include <unistd.h>
Include windows.h Library In Windows
If we are writing an application which will run on the windows platform we should include windows.h
library like below.
#include <Windows.h>
Cross-Platform Library Solution
Actually there is no cross plat format default library. But we can write our application which will use the proper library according to compile architecture. In this case, we will use _WIN32
constant which will put the appropriate library accordingly.
#ifdef _WIN32 #include <Windows.h> #else #include <unistd.h> #endif
Sleep Example App
In this part, we will use sleep()
function in an example. In this example, we want to sleep for 1 second. As we can see the parameter will be 1
which is an integer.
#include<stdio.h> main() { printf("Sleeping for 1 second.\n"); sleep(1); return 0; }
Sleep For 10 Second
We can also sleep for 10
seconds without a problem. We will just provide the 10
to the sleep
function like below.
#include<stdio.h> main() { printf("Sleeping for 1 second.\n"); sleep(10); return 0; }
Sleep For 100 millisecond
As stated previously the sleep function will interpret given value as the second. What if we need to sleep in milliseconds which is lower than second. We can use decimal or float values. In this example, we will sleep for 10
millisecond which can be expressed like 0.01
or 0.010
#include<stdio.h> main() { printf("Sleep for 10 milisecond to exit.\n"); sleep(0.10); return 0; }
Sleep Microsecond with usleep() Function
We can also use usleep()
function which will sleep given value in a microsecond. In this case, we will sleep for 10
microsecond with usleep()
function.
#include<stdio.h> main() { printf("Sleep for 10 milisecond to exit.\n"); usleep(10); return 0; }
Return Value
The sleep()
function will return void which means it will not return anything.
Thank you, a Nice article which help me to understand the concept of sleep () function.
usleep actually sleeps for the given number of *microseconds*, not milliseconds as stated in the article.
Thanks for your correction.
`usleep()` sleeps for *microseconds*, NOT milliseconds!
http://man7.org/linux/man-pages/man3/usleep.3.html
Thanks for your correction.
In the example that sleeps for 10 seconds, it still says “Sleeping for 1…”
At the beginning of the article, it references “slepp()”, not “sleep()”…
Thanks for the help. We have corrected it.
I think it should be Sleep() on windows.
(uppercase S)
The function call:
sleep(0.10);
will sleep for 0.100 seconds. This is 100 milliseconds not 10 milliseconds.