Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Block a thread with sleep vs block without sleep

I've created a multi-threaded application using C++ and POSIX threads. In which I should now block a thread (main thread) until a boolean flag is set (becomes true).

I've found two ways to get this done.

  • Spinning through a loop without sleep.

    while(!flag);
    
  • Spinning through a loop with sleep.

    while(!flag){
         sleep(some_int);
    }
    

If I should follow the first way, why do some people write codes following the second way? If the second way should be used, why should we make current thread to sleep? And what are disadvantages of this way?

like image 845
frogatto Avatar asked Jun 28 '15 18:06

frogatto


People also ask

Why is thread sleep not recommended?

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

Does sleeping a thread block it?

Sleep method. Calling the Thread. Sleep method causes the current thread to immediately block for the number of milliseconds or the time interval you pass to the method, and yields the remainder of its time slice to another thread.

Is it good practice to use thread sleep?

Using Thread. sleep() frequently in an automation framework is not a good practice. If the applied sleep is of 5 secs and the web element is displayed in 2 secs only, the extra 3 secs will increase the execution time. And if you use it more often in the framework, the execution time would increase drastically.

What is difference between calling wait () and sleep () method in Java multithreading?

Wait() method releases lock during Synchronization. Sleep() method does not release the lock on object during Synchronization. Wait() should be called only from Synchronized context. There is no need to call sleep() from Synchronized context.


1 Answers

The first option (a "busy wait") wastes an entire core for the duration of the wait, preventing other useful work being done and/or wasting energy.

The second option is less wasteful - your waiting thread uses very little CPU and allows other threads to run. But it is still wasteful to keep switching back to the thread to check the flag.

Far better than either would be to use a condition variable, which allows the waiting thread to block without consuming any resources until it is able to proceed.

like image 90
Alan Stokes Avatar answered Oct 27 '22 01:10

Alan Stokes