systhread_mutex_lock vs systhread_mutex_trylock

Jan 11, 2012 at 10:29am

systhread_mutex_lock vs systhread_mutex_trylock

What is the best way of choosing between mutex_lock and mutex_trylock?
What does mutex_lock do when the mutex is already locked? does it wait?

I looked at the ‘collect’ example and there is no mention of mutex_trylock. Is that on purpose?



Jan 11, 2012 at 3:25pm



- with mutex_lock the thread sleeps until the mutex is released (and the thread waked up) ;
- with mutex_trylock it just abort.

instead of mutex_trylock i use something like that …

if (ATOMIC_INCREMENT (&x->lock) == 1) {
} else {

… but i’m not sure it is best ;-)

Feb 1, 2012 at 1:51pm

Hello vanille,

you’re right
thanks for the response, sorry for my delay in responding

I did a little test and yes, the mutex_lock sleeps the current thread. Another thread can still unlock it.


Feb 1, 2012 at 3:12pm


i use ATOMIC for anything i can delay (like GUI) …

if not busy :
do the stuff
else :
try later

… in kind of custom event poll loop but that is my 2 cents ;-)

ATOMIC seems to be more efficient than tryLock :

Feb 1, 2012 at 5:20pm

curious: what is your recipe for delaying the message inside the external?

Feb 1, 2012 at 6:16pm


i code this trick mainly for GUI :

I use bit mask to set flags NEED_TO_DRAW_THAT, NEED_TO_DRAW_THIS etc … i create a clockTask polling every 40 ms (for instance) and copy data according to bit set (then ask jbox_redraw to do the job). Of course it slows the drawing rate, but i don’t really care. It’s to isolate the paint method.

For now, it’s a little bit messy, but seems efficient ; next step is to encapsulate the process in a library in a cleaner way (code is on github anyway).

Feb 2, 2012 at 12:56am

FWIW I also use lightweight thread sync stuff based on atomic operations a lot of the time, including when I need to wait till the lock is free. In this case you can spin on a while loop until it is free or similar . The thread will be consuming cycles, but that is often IMHO preferable to sleeping threads for short periods in real-time contexts…


Feb 2, 2012 at 7:06am

interesting, thanks guys.

alex, why is in your opinion spinning on a while loop preferred to sleeping a thread?
isn’t that basically the same thing? or do I miss something.

Feb 2, 2012 at 10:58am


With mutex there is no spin ; if mutex is lock, querying thread go to sleep, when the mutex is released, one from the sleeping threads is waked up, but there is no guarantee about waking up order.

Spinning avoid your thread to sleep ; synchronisation is more “accurate” since you can continue just after the lock is ok ; but with CPU cost ;-)


You must be logged in to reply to this topic.