Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static lock_guard with static mutex too?

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.

like image 870
hg_git Avatar asked Mar 09 '23 20:03

hg_git


1 Answers

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.

like image 58
Slava Avatar answered Mar 17 '23 11:03

Slava