0

say I have 3 types of threads:

//Thread_1:
lock(mutex)
while(t1_unexceptable_cond){
    wait(t1_cv, mutex);
}
//TAKE RESOURCES
if(should_signal_T2){
    signal(t2_cv, mutex)
} else {
    signal(t1_cv, mutex)
}
unlock(mutex)
//DO THINGS WITH RESOURCES
lock(mutex)
//RETURN RESOURCES
unlock(mutex)

//Thread_2:
lock(mutex)
while(t2_unexceptable_cond){
    wait(t2_cv, mutex);
}
//ACQUIRE RESOURCES
if(should_signal_T2){
    signal(t2_cv, mutex)
} else {
    signal(t1_cv, mutex)
}
unlock(mutex)
//DO THINGS WITH RESOURCES
lock(mutex)
//RETURN RESOURCES
unlock(mutex)

//Thread_3:
lock(mutex)
//DO THINGs
unlock(mutex)

If I have a series of thread_1s and thread_2s waiting on the mutex, will a thread_3 starve since the other threads are getting signaled? I would assume the other threads would go first upon waking up, thus instances of thread_3 would never get a chance to run. Is my thought process correct here?

whytheman
  • 129
  • 2
  • 6

1 Answers1

0

I don't think so. Your both thread_1s and thread_2s have this code:

lock(mutex)
//RETURN RESOURCES
unlock(mutex)

How's it different from thread_3?

Also, mutex is not held while waiting on a conditional variable, it will be re-acquired by a thread when it's got signalled. So, in the worst case, we have continuous lock contention here. But unless the threads have different priorities, all the threads are have the same chances to starve, not only thread_3, it rather depends on the timings between the locks. But if the starvation really takes a place, try to use a fair mutex, e.g. as described here

Community
  • 1
  • 1
Anton
  • 6,349
  • 1
  • 25
  • 53