简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM