Question

I'm new to multithreading and I ran into a two questions about thread scheduling with thread.yield and sleep in which I couldn't find a clear anwser to from my book or with googling. I'm going to save all pseudo codes or real codes because I think I already understand the possible starvation problem if my assumptions aren't right.

I'm going to refer to 3 pseudo threads in my questions:

  1. My first question is that if I call thread yield or sleep in one of my 3 threads, is it guaranteed that CPU tries to schelude and process the other 2 threads before it comes back to the thread which called yield? So basically are threads in a clear queue, that makes the yiealding thread go to last of the queue?

I know that yield should give other threads chance to run but is it possible for example that after the yielding thread one of the 2 other threads tries to run and after that it goes back to the original thread which called yield, skipping the last thread and not giving it a chance to run at all?

  1. My second question is related to the first. So do yield and sleep both have the same propeties that they both go to be the last on the queue when called like I assumed in my first question or is there anything other differences between them but the sleeping time in sleep?

If these question doesn't make sense the possible problem in my code is that before the thread which goes to sleep it has unlocked a mutex which one of the other threads has tried locking before, failed and gone waiting for it to open. So after the thread has gone to sleep, is it guaranteed that the thread which tried to lock the mutex will lock it before the sleeping thread?

Was it helpful?

Solution

Thread.yield() is a hint to thread scheduler which means "hey, right now I feel ok if you alseep me and let other thread run". There is no guarantees, it is only a hint. The assumption about the ordering of threads in "queue" is also incorrect because thread scheduling is done also by OS and it is very hard to predict a particular exection order without additional thread interaction mechanisms.

Thread.sleep() puts current thread to sleep for a specified amount of time, so the answer to your second question is - no, they do different things.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top