Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will a thread sleep if told to sleep for zero seconds?

Tags:

c++

sleep

My question is simple. If I use std::this_thread::sleep_for(0ms), will the thread sleep at all?

I know this seems like a silly question, but when I tell a thread to sleep for a very small amount (such as 10 microseconds), it often sleeps for at least 5-10 milliseconds. I know this is related to how operating systems schedule their processes. I just want to know how all of the corner cases work, as I have some code that may be slowing down due to sleeping for small, zero, or negative amounts of time.

EDIT 1: I have simplified the question to just be about sleeping for zero seconds.

EDIT 2: Many comments so far has been about how I shouldn't try to do this, but I both have a reason and I'm curious. In my code, I am not literally calling std::this_thread::sleep_for(0ms), but instead, I am sleeping for a variable amount of time based on external conditions. When I compute the amount of time I need to sleep, the result can be positive, negative, or zero. I want to know if I am still sleeping for results less than or equal to zero.

like image 283
qhs190 Avatar asked Sep 06 '19 17:09

qhs190


People also ask

What happens to a thread when it sleeps?

Thread. sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.

What does thread sleep 0 do in Java?

sleep in Java. Thread. sleep() method can be used to pause the execution of current thread for specified time in milliseconds.

How long is thread sleep 1000?

sleep time means more than what you really intended. For example, with thread. sleep(1000), you intended 1,000 milliseconds, but it could potentially sleep for more than 1,000 milliseconds too as it waits for its turn in the scheduler. Each thread has its own use of CPU and virtual memory.

Why thread sleep is not recommended?

Thread. sleep is bad! It blocks the current thread and renders it unusable for further work.


1 Answers

The most common behavior that I've observed on typical platforms is that it acts like a voluntary yield operation. That is, it will do nothing unless there is another ready-to-run thread that is not currently scheduled, in which case it will yield to that thread.

There are no specific requirements on how the platform handles this case. Treating as a no-op would be perfectly reasonable. Treating it as the shortest sleep the platform could support would also be perfectly reasonable.

like image 137
David Schwartz Avatar answered Oct 11 '22 14:10

David Schwartz