QQCompi
QQCompi

Reputation: 225

Thread Synchronization C++

I am having this weird issue with threads. On my mac with OS X this works fine but once I more it over to my desktop that is running Ubuntu, I am facing issues.

Essentially what I am doing is the following:

Function() {

   for(i = 1 to 10)
      while(array not completely changed) {
         pthread_mutex_lock(&lock);
         -- perform actions
         pthread_mutex_unlock(&unlock);
      }
   }
}

And I have two threads running this function. While it is supposed to be running in such a manner that is:

Thread 1 grabs lock
performs opperations on array
Thread 1 releases lock
Thread 2 grabs lock
performs calculations on array
Thread 2 releases lock

and so on in a back and forth pattern until the array have been completed changed but on Linux all of the calculations of Thread 1 complete and then Thread 2 starts.

So I will get:

Thread 1 grabs lock
performs opperations on array
Thread 1 releases lock
Thread 1 grabs lock
performs calculations on array
Thread 1 releases lock
Thread 1 grabs lock
performs calculations on array
Thread 1 releases lock

And so on until the array is completely changed, once I increment the for loop, then Thread 2 will perform all calculations and continue this pattern.

Can anyone explain what is going on?

Upvotes: 1

Views: 335

Answers (1)

Craig Estey
Craig Estey

Reputation: 33631

You're experiencing "starvation". Add a small nanosleep call occasionally to give the other threads a chance to run. Add the call outside the mutex pair (e.g. after the unlock). Thread 1 is monopolizing things.

You may also want to consider restructuring and splitting up the critical [requires locking] vs non-critical work:

while (more) {
    lock ...
        do critical stuff ...
    unlock ...
    nanosleep ...
    do non-critical stuff
}

Upvotes: 4

Related Questions