Intel® oneAPI Threading Building Blocks
Ask questions and share information about adding parallelism to your applications when using this threading library.
2477 Discussions

How can I know whether a mutex is locked or free?

LU__Baotong
Beginner
2,382 Views

Hello,

I am implementing a function that the thread need to know the state of the mutex(i.e. locked or free). But I find that TBB mutex does NOT provide such a function interface. 

There is a function named "bool M::scoped_lock::try_acquire(M&) " providing a similar action but it can acquire the lock on it if the mutex is free. I just wanna know the state of the mutex rather than acquire the lock on the mutex if it's free.

Can someone help me? How can I achieve my goal? Thanks!

Ray

 

0 Kudos
1 Reply
Nikita_P_Intel
Employee
2,382 Views

Hi Ray!

Generally, you can't reasonably check whether a mutex is locked, because of the race between checking the "state" of the mutex and possible locking/unlocking by another thread. Maybe you could just introduce a boolean flag after mutex::lock/unlock() calls and check when necessary. But still "M:try_lock()" seems to be more reliable. Please, provide the details of your situation, maybe there is another solution for your problem?

-Nikita

0 Kudos
Reply