lundi 30 janvier 2017

Assure, function runs under lock_guard

I have a function foo() which is called from different places in a heavy multi-threaded environment.

It is modifying some sensitive data but due to the complexity I cannot use inside this function std::lock_guard... - this must be assured by the caller function. The reason is that the function is called several times in a row and the modified data [inside foo()] must not be touched in the meantime by other thread until the one thread finished all modifications by the several calls of foo().

We all are human - and especially me - and I was thinking about a way how to assure that the function foo() is indeed under the lock_guard... control and I just didn't forget to lock the scope.

For me - running under gcc and I don't have to consider any platform independent solution - I found this way:

auto foo( __attribute__ ((unused)) std::lock_guard<std::mutex> & guardActive ) -> void
{
   ...
}

Then, foo() must be called like this, otherwise already gcc does not compile it:

std::lock_guard<std::mutex> lockScope( mutexObject );
...
foo( lockScope );
...

My question:

Is this way OK, or are there better solutions? Reentrant mutex cannot be used.

Aucun commentaire:

Enregistrer un commentaire