Assume that the following code is being executed by 10 threads.
pthread_mutex_lock(&lock)
Some trivial code
pthread_mutex_unlock(&lock)
(The first two attempts had bugs, pls jump to EDIT2)
Maybe this would work?
if NOT this thread is T1 or T2 or T3
pthread_mutex_lock(&lock1) // see note below
pthread_mutex_lock(&lock2)
Some trivial code
pthread_mutex_unlock(&lock2)
pthread_mutex_unlock(&lock1)
else
pthread_mutex_lock(&lock2)
Some trivial code
pthread_mutex_unlock(&lock2)
end if
Reasoning:
Some threads will compete for two locks and therefore will have lower priority and some threads will compete for only one lock and therefore will have higher priority.
Still the difference might be marginal and then the resolution would be to introduce some lag between acquiring first lock and attempting the second lock for the higher priority threads in which time the higher priority threads will be given a chance to get the lock2.
(disclaimer: I am a newbie when it comes to this)
EDIT: Another attempt/approach
if NOT (this thread is T1 or T2 or T3)
pthread_mutex_lock(&lock1)
if pthread_mutex_trylock(&lock2) == 0 // low priority threads will not get queued
Some trivial code
pthread_mutex_unlock(&lock2)
end if
pthread_mutex_unlock(&lock1)
else
if (this thread is T1 or T2 or T3)
pthread_mutex_lock(&lock2)
Some trivial code
pthread_mutex_unlock(&lock2)
end if
end if
EDIT2: Another attempt (trying to learn something here)
if NOT (this thread is T1 or T2 or T3)
pthread_mutex_lock(&lock1)
while !(pthread_mutex_trylock(&lock2) == 0)
pthread_yield()
Some trivial code
pthread_mutex_unlock(&lock2)
pthread_mutex_unlock(&lock1)
else
if (this thread is T1 or T2 or T3)
pthread_mutex_lock(&lock2)
Some trivial code
pthread_mutex_unlock(&lock2)
end if
end if