Check to see if a pthread mutex is locked or unlocked (After a thread has locked itself)

后端 未结 3 1707
孤城傲影
孤城傲影 2020-11-29 06:54

I need to see if a mutex is locked or unlocked in an if statement so I check it like this...

if(mutex[id] != 2){
    /* do stuff */
}

but w

3条回答
  •  鱼传尺愫
    2020-11-29 07:28

    You can use pthread_mutex_trylock. If that succeeds, the mutex was unclaimed and you now own it (so you should release it and return "unheld", in your case). Otherwise, someone is holding it.

    I have to stress though that "check to see if a mutex is unclaimed" is a very bad idea. There are inherent race conditions in this kind of thinking. If such a function tells you at time t that the lock is unheld, that says absolutely nothing about whether or not some other thread acquired the lock at t+1.

    In case this is better illustrated with a code example, consider:

    bool held = is_lock_held();
    
    if (!held)
    {
      // What exactly can you conclude here?  Pretty much nothing.
      // It was unheld at some point in the past but it might be held
      // by the time you got to this point, or by the time you do your
      // next instruction...
    }
    

提交回复
热议问题