0

sleep() blocks the running thread in C given x amount of seconds. If I'm not mistaking, this can be implemented in 2 ways. Either go in an infinite loop and check the current time with BIOS, if time>=timeout then end the loop.

Second way is to use a timer in CPU and let the timer do the counting async and not block the CPU thread.

Am I correct about the above 2 methods? if so why doesn't C have a function to implant the second way so we can have non-blocking "delays"?

6
  • 2
    Because there is no native support to asynchronous computing in C, you have to use a library such as pthread. Commented Jul 7, 2020 at 1:48
  • but theoretically speaking, sleep could have had an async version a swell right? nothing is stopping the hardware from doing it. Commented Jul 7, 2020 at 1:50
  • 1
    Depends on the hardware. C is designed to be used to program just about anything, from last gen games to 8-pin microcontrollers smaller than a grain of rice, so the language isn't tied to features that would limit it to advanced hardware. Commented Jul 7, 2020 at 1:54
  • 1
    The question seems to mix up two things: sleep() which blocks the program (or thread) but hopefully doesn't block the CPU (so that other threads or processes can run), and asynchronous timers like the non-ISO alarm() that let the program keep running and notify it after a certain length of time. It is entirely possible for the OS to implement sleep in your "second way" without a busy loop, by switching to another process (or halting the CPU) and letting a timer interrupt cause a switch back when the timeout expires. Commented Jul 7, 2020 at 1:59
  • Because that requires a thread or an event loop. Commented Jul 7, 2020 at 2:04

1 Answer 1

4

There's another way, which is the one which is usually behind a call to sleep(): tell the kernel scheduler to remove this process from the runnable set until the time has expired.

For the function which sets a timer and tells you when it is finished, you can start by looking at alarm() and pause(). Those aren't in the standard C library, but they have been in Posix for a very long time.

On Windows, you could look at SetTimer.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.