Resource Collection and pthreads

I am acquiring some resources in ascending order. Which version is better? I was told that No. 2 leads to starvation of threads requiring higher resources. It's 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 the order in which you free resources makes a difference, not over constructs. If you release them so that you receive them, fasting happens, if in the opposite case, probably not.

+5
source share
3 answers

Both will be virtually equivalent, since in Example 1, the thread will almost always restore the mutex that does not sleep immediately after it is unlocked, since only two expressions are calculated between them.

+3

, , pthread_cond_wait . . , N , , , , .

, nescesarry, .

, - , . , / for . . , , i. , , .

 // blocks till resource resourceNum is obtained
 void acquire_resource(int resourceNum)
 {
     lock(mutex)
     while(!resource_available[a[i]]) {
       pthread_cond_wait(&cond_w[a[i]], &mutex);
     }
     unlock(mutex)
 }

 for(int i = 1; i < N; ++i) {
     acquire_resource(i);
 }
+2

I would have a lock and unlock in the function resource_available, and then lock right before the wait - unlock immediately after it.

0
source

All Articles