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

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

C programming language provides slepp() 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 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.

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.

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.

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.

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

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.

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

Return Value

The sleep() function will return void which means it will not return anything.

5 Responses

  1. Thank you, a Nice article which help me to understand the concept of sleep () function.

  2. Filip Haglund says:

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

  3. Gabriel Staples says:

    usleep() sleeps for *microseconds*, NOT milliseconds!

Leave a Reply

Your email address will not be published. Required fields are marked *

Enjoy this blog? Please spread the word :)