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

mutable and thread safety

robert_jay_gould
Beginner
399 Views

This is probably notnecessarilyTBB related, but can an tbb::atomic or a tbb::mutex be mutable?

I have this const function, that calls some of my code (can't change the caller), that reads data out from an object.But internally during this call I need to ensure that the data is not being changed by another thread, so I was placing a scoped lock in the call, problem is locking/unlocking require the object to not be constant, since the lock is part of the object. So I'm not sure if I should cast away the the constness of the entire object within the callback, or if its possible to make thesynchronizationprimitive mutable (keyword).

0 Kudos
3 Replies
Dmitry_Vyukov
Valued Contributor I
399 Views

This is probably notnecessarilyTBB related, but can an tbb::atomic or a tbb::mutex be mutable?

I have this const function, that calls some of my code (can't change the caller), that reads data out from an object.But internally during this call I need to ensure that the data is not being changed by another thread, so I was placing a scoped lock in the call, problem is locking/unlocking require the object to not be constant, since the lock is part of the object. So I'm not sure if I should cast away the the constness of the entire object within the callback, or if its possible to make thesynchronizationprimitive mutable (keyword).

I don't see any problems in declaring mutex or atomic as mutable. Also you can cast away the constness only from mutex before locking.

0 Kudos
robert_jay_gould
Beginner
399 Views
Quoting - Dmitriy Vyukov

I don't see any problems in declaring mutex or atomic as mutable. Also you can cast away the constness only from mutex before locking.

Thanks, I wasn't sure if mutable might have some sort of effect on handling and loading the values in the registers.

0 Kudos
ARCH_R_Intel
Employee
399 Views

In almost all cases, const gives code generators no useful information and consequently has no effectonlow-level code generation. The reason is twofold:

  • const can be cast away
  • const does not prevent modification via other pointers to the same target location

If the compiler can prove these two reasons do not apply, it has enough information to do the optimization anyway without the const. The few signifcant contexts where an optimizer can exploit const are:

  • The const is on the original object declaration, and thus the object is known to be immutable over its lifetime modulo any mutable keywords.
  • The const is on the target of a pointer marked restrict (C99), and thus is known to be immutable over the scope of the pointer. [I'm begin deliberately vague about "scope" - see C99 standard for details.]
0 Kudos
Reply