Home > Software engineering >  Thread.Sleep. Suspends the current thread what does that mean?
Thread.Sleep. Suspends the current thread what does that mean?

Time:07-21

Thread.Sleep. Suspends the current thread what does that mean? What does this mean physically? What does a thread do? It cannot be said that the thread does nothing because the method itself is executed and the thread must do something, and if the thread does something, then it is not suspended or is it not?

CodePudding user response:

Modern operating systems can assign CPU time to multiple processes, each of which may contain multiple threads.

A component often called a scheduler is responsible for this.

Calling Thread.Sleep() informs the scheduler that a given thread should not run until at least a specified amount of time has passed. The scheduler will use that information to allocate CPU time to other threads.

CodePudding user response:

Thread.Sleep. Suspends the current thread what does that mean?

From the application's point of view it's simple. Thread.sleep(n) does nothing. It does it for n milliseconds, and then it returns.

What does this mean physically?

On a multi-tasking operating system (e.g., most desktop, server, or mobile-device platforms) it means that the OS scheduler allows the CPU that the thread was running on to be used for other things during the next n milliseconds. If there are no other threads at that moment that are ready to run, then the scheduler allows a special "idle loop" to run on it. The "idle loop" puts the CPU into a low-power state until it gets an interrupt signifying that the CPU is needed again.

What does a thread do?

Think of a thread as an agent who executes your code.

It cannot be said that the thread does nothing because the method itself is executed...

You can say that if you wish. The sleep() function "does nothing" in the sense that it doesn't cause the CPU to do any work, it has no side effects, and it returns no value. But I guess it makes sense to say that the thread is "doing something" during the sleep() interval. Specifically, what the thread is doing is, it is sleeping. More broadly speaking, the thread is executing your code, which just that that exact moment, is telling the thread to sleep.

..., and if the thread does something, then it is not suspended or is it not?

Suppose you are planting a garden. It's going to take you all day, but at some point, you have to take a break and get some water. Your phone rings just at that moment and your friend asks, "Yo Bro! What's up?" Would it be acceptable for you to say, "I'm planting a garden...?" IMO you could say that. Or, you could say, "I'm taking a break from planting a garden," or if you wanted to be a smart-ass, you could say "I'm talking to you on the phone." All three of those arguably are true statements.

You taking a break to get some water is kind of like a thread being "suspended."

  • Related