#Acquiring a Mutex in a Loop

5 messages · Page 1 of 1 (latest)

sterile shadow
#

Hey, I have a worker thread that wants to do as much work with a mutex as possible. Unfortunately, some other threads wants to look at the internal work of the thread (every few ms). I wrote this loop so the mutex gets freed every 1000 units or so (so other threads can acquire it).

But on some computers the other threads are barely able to acquire this mutex (takes like 8 seconds). I found adding a sleep after releasing the mutex works for these computers, but that effectively caps the amount of work I can do. What's the right way I can make this mutex available to other threads while still doing computation as fast as possible?

loop {
    {
        let mut m = mutex.lock().unwrap();
        
        do_1000_units_of_computation(&mut m);
    }
    
    // mutex freed until the next loop
}
mortal warren
#

What you want is a fair mutex, which means the thread that acquires the lock is always the one that's been waiting the longest. This ensures that when you call lock at the beginning of the loop, anything that wanted to read it will be able to. Parking_lot has a fair mutex: https://docs.rs/parking_lot/latest/parking_lot/type.FairMutex.html The one in the standard library doesn't have a specified fairness, and is likely unfair since that's cheaper.

sterile shadow
#

Okay! That's awesome! How much performance am I actually giving up here out of curiosity

#

not that i have a choice

mortal warren
#

I dunno, but probably not a lot.