简体   繁体   中英

C Pthreads mutex values?

I am writing a program with a few critical sections. The thing is I need to check the value of a mutex in an if statement.

I would like to do something like this:

if pthread_mutex(&mutex) == 0 // locked 
  // Do something
else if pthread_mutex(&mutex) == 1 // unlocked 
 // Do something else

Is this possible?

You want pthread_mutex_trylock() .

From that link:

The pthread_mutex_trylock() function shall be equivalent to pthread_mutex_lock(), except that if the mutex object referenced by mutex is currently locked (by any thread, including the current thread), the call shall return immediately. ... Return values ... The pthread_mutex_trylock() function shall return zero if a lock on the mutex object referenced by mutex is acquired. Otherwise, an error number is returned to indicate the error

So your code would go like this:

pthread_mutex_t *m = /* ... */;

if (pthread_mutex_trylock(m) == 0)
{
    /* Success!  This thread now owns the lock. */
}
else
{
    /* Fail!  This thread doesn't own the lock.  Do something else... */
}

No you shouldn't try to do that. I think, pthread mutexes are made to regulate local access to some critical resource, and if at a place your program doesn't know if this actual thread holds the lock, you are using the wrong tool. I see two alternatives:

  • keep a variable on the stack of the function where you keep track that it is locked here, or if really necessary store the thread id and compare to that
  • switch to sem_t as control DS. they don't have this restriction of being glued to a specific thread that "holds" them, but are token based, so any thread that obtains the token may do the work that is required. (but be careful and check the return value of the functions these routines may be interrupted.)

If you want to know if your mutex is already locked, I suggest you use pthread_mutex_trylock . Keep in mind that locking a mutex is an heavy operation, you shouldn't lock it just to test if it wasn't.

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