JDoe4444
JDoe4444

Reputation: 35

Why doesn't my mutex lock before my other thread locks it?

I am running 1 thread created with pthreads and I'm using a mutex between the thread and my main thread. From what I understand, once a thread is ready to lock a mutex, it will spinlock until its able to lock. But I'm running into an issue where it doesn't spinlock. The pseudo code I have.

Main thread:

//I create thread 1 on this line, then it enters the while loop
while(p.size() > r.size()){
  pthread_mutex_lock(&Mutex);
  //calculations and decrease p.size()
  pthread_mutex_unlock(&Mutex);
}

Thread 1:

//wait 500ms before hitting mutex
pthread_mutex_lock(&Mutex);
//calculations
pthread_mutex_unlock(&Mutex);

The issue I'm running to is that the Thread 1 Mutex never locks until the main thread while loop exits. Thread 1 reaches the mutex lock before the main thread can finish the while loop.

EDIT: If I had a delay of 10ms to the end of my while loop (after the mutex unlocks), then this fixes my problem. But how can I fix the problem without adding a delay of 10ms.

Upvotes: 1

Views: 2222

Answers (1)

Humphrey Winnebago
Humphrey Winnebago

Reputation: 1682

Your main thread is unlocking the mutex and then immediately locking it again. Try introducing a delay in your main loop (for testing purposes) to see if this is the issue.

Check out the answer to this question: pthreads: thread starvation caused by quick re-locking

Upvotes: 3

Related Questions