What Is sleep() function and How To Use It In C Program?


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.

LEARN MORE  How To Pause and Resume Powershell and Cmd Scripts In Windows With Examples?

10 thoughts on “What Is sleep() function and How To Use It In C Program?”

  1. usleep actually sleeps for the given number of *microseconds*, not milliseconds as stated in the article.

    Reply
  2. The function call:
    sleep(0.10);
    will sleep for 0.100 seconds. This is 100 milliseconds not 10 milliseconds.

    Reply

Leave a Comment