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

tbb::mutex::scoped_lock

jswift2
Beginner
280 Views
Hi folks,

Can someone explain the rationale behind the constructor design for scoped_lock?
It's a little surprising that it can only be constructed with an unacquired mutex.

//! Acquire lock on given mutex.
/** Upon entry, *this should not be in the "have acquired a mutex" state. */
scoped_lock( mutex& mutex ) {
acquire( mutex );
}

I would have expected it to simply block upon construction until the mutex is acquired.
Is it something to do with sequence points?

thanks,

James
0 Kudos
2 Replies
RafSchietekat
Valued Contributor III
280 Views

"It's a little surprising that it can only be constructed with an unacquired mutex."

That comment is confusing or perhaps even wrong: the scoped_lock does what you think it should do (potentially block until the current owner releases the mutex).

Maybe the "not" should be removed, meaning that after construction it is 'in the "have acquired a mutex" state'? Maybe the "should" should be 'would', meaning that the "acquire()" call is safe at that point? I don't know.

It does seem peculiar that there's no check for NULL!=my_mutex to protect against misuse. This constructor would then also have to initialise my_mutex to NULL before calling acquire(), but at least you get early failure if you call acquire() on a lock that's already locked, at negligible cost.

0 Kudos
Alexey-Kukanov
Employee
280 Views

I agree the comment is misleading. It is appropriate for the method acquire() but not for the constructor of the scoped_lock class.

And of course Raf is right that the constructor will do just what you expect.

0 Kudos
Reply