mutex locking
Hi all,
my question is about the right way to lock and inquire a mutex. At time, my code looks like this:
rt_mutex_inquire(&mutex,TM_NONBLOCK);
if(info.lockcnt == 0)
{
rt_mutex_lock(&write_mutex,TM_NONBLOCK);
// do sth.
rt_mutex_unlock(&mutex);
}What happens if anyone locks the mutex between my "rt_mutex_inquire(...)" and my "if(info.lockcnt == 0)" ?
Is this the standard way to lock and inquire a mutex?
Thanks,
Tobias
Quoted 17 lines · Tobias Bär
Hi all,
my question is about the right way to lock and inquire a mutex. At time, my code looks like this:
rt_mutex_inquire(&mutex,TM_NONBLOCK);if(info.lockcnt == 0)
{ rt_mutex_lock(&write_mutex,TM_NONBLOCK); // do sth. rt_mutex_unlock(&mutex); }
Quoted 4 lines
What happens if anyone locks the mutex between my "
rt_mutex_inquire(...)" and my "if(info.lockcnt == 0)" ?Is this the standard way to lock and inquire a mutex?
Try this, it's safe from such races:
/* returns -EWOULDBLOCK if the mutex is locked */
if (rt_mutex_lock(&write_mutex,TM_NONBLOCK) == 0)
{
// do sth.
rt_mutex_unlock(&mutex);
}Jan
Quoted 17 lines · Tobias Bär
Hi all,
my question is about the right way to lock and inquire a mutex. At time, my code looks like this:
rt_mutex_inquire(&mutex,TM_NONBLOCK);if(info.lockcnt == 0)
{ rt_mutex_lock(&write_mutex,TM_NONBLOCK); // do sth. rt_mutex_unlock(&mutex); }
Quoted 3 lines
What happens if anyone locks the mutex between my "
rt_mutex_inquire(...)" and my "if(info.lockcnt == 0)" ?Is this the standard way to lock and inquire a mutex?
No, this snippet is terminally broken, I'm afraid. The mutex object is precisely aimed at avoiding this kind of race conditions; the code above would introduce them back.
Native skin mutexes are recursive by nature, so there is no need to inquire for their current status. Additionally, passing TM_NONBLOCK might cause mutex_lock() to return an error, if another thread holds it already, so you need to check for the return value in any case. What you likely want is, either:
if (rt_mutex_lock(...TM_INFINITE) < 0)
bail_out();
/* work in critical section */rt_mutex_unlock()
or,
if (rt_mutex_lock(...TM_NONBLOCK) < 0)
resource_not_immediately_available();
/* work in critical section */rt_mutex_unlock()
Quoted 8 lines
Thanks,
Tobias_______________________________________________
Xenomai-help mailing list
[email protected]
https://mail.gna.org/listinfo/xenomai-help
Signature · 1 line
Philippe.