I'm acquiring some resources in increasing order. Which version is better? I was told that #2 leads to starvation of threads wanting higher numbered resources. Is this true? If so, how and why?
a[] sorted array
1.
for(int i = 1; i < N; ++i) {
lock(mutex)
while(!resource_available[a[i]]) {
pthread_cond_wait(&cond_w[a[i]], &mutex);
}
resource_available[a[i]] = 0;
unlock(mutex)
}
2.
lock(mutex)
for(int i = 1; i < N; ++i) {
while(!resource_available[a[i]]) {
pthread_cond_wait(&cond_w[a[i]], &mutex);
}
resource_available[a[i]] = 0;
}
unlock(mutex)
EDIT: It turns out that order in which you release resources makes the difference, not above constructs. If you release them in order you received them starvation happens, if in opposite then probably not.