Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multithreading, when to yield versus sleep

To clarify terminology, yield is when thread gives up its time slice. My platform of interest is POSIX threads, but I think the question is general.

Suppose I have consumer/producer pattern. If I want to throttle either consumer or producer, which is better to use, sleep or yield? I am mostly interested in efficiency of using either function.

like image 398
Anycorn Avatar asked Apr 19 '10 15:04

Anycorn


People also ask

Why thread sleep is not recommended?

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

Under what circumstances might you use the yield method of the thread class?

Use of yield method:If the processor finds any thread with higher or same priority then it will move the current thread to Ready/Runnable state and give the processor to another thread and if not – the current thread will keep executing.

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.

What is yield () and sleep () in thread Java?

3.2. While yield() can only make a heuristic attempt to suspend the execution of the current thread with no guarantee of when will it be scheduled back, sleep() can force the scheduler to suspend the execution of the current thread for at least the mentioned time period as its parameter.


1 Answers

The "right" way to code a producer / consumer is to have the consumer wait for the producer's data. You can achieve this by using a synchronization object such as a Mutex. The consumer will Wait on the mutex, which blocks it from executing until data is available. In turn, the producer will signal the mutex when data is available, which will wake up the consumer thread so it can begin processing. This is more efficient than sleep in terms of both:

  • CPU utilization (no cycles are wasted), and
  • Run Time (execution begins as soon as data is available, not when a thread is scheduled to wake up).

That said, here is an analysis of yield vs sleep that you asked for. You may need to use such a scheme if for some reason waiting for output is not feasible:

It depends how much traffic you are receiving - if data is constantly being received and processed, you might consider doing a yield. However in most cases this will result in a "busy" loop that spends most of its time needlessly waking up the thread to check if anything is ready.

You will probably want to either sleep for a short period of time (perhaps for less than a second, using usleep) OR even better use a synchronization object such as a mutex to signal that data is available.

like image 169
Justin Ethier Avatar answered Sep 20 '22 13:09

Justin Ethier