So I've some thread-unsafe function call which I need to make thread safe so I'm trying to use a std::mutex
and a std::lock_guard
. Currently code looks like this -
int myFunc(int value){
static std::mutex m;
std::lock_guard lock(m);
auto a = unsafe_call(value);
return a;
}
the unsafe_call()
being the thread-unsafe function. I've also put static around the mutex because then the function will have different mutexes for each separate call.
What I want to know is, should I also make lock_guard
static because the mutex is static one, as I was told by some coworker of mine. I don't see a reason why should I do this, because I consider lock_guard
to be a simple .lock()
and .unlock()
call, but the suggestion from coworker is confusing me.
should I also make lock_guard static because the mutex is static one, as I was told by some coworker of mine.
Your coworker is completely wrong, lock_guard
is using RAII mechanism to control resource (mutex in this case) and making it static would completely defeat it's purpose - mutex would be locked once on the first execution of the function and released only when program terminates, ie effectively you would not be using mutex at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With