简体   繁体   中英

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.

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.

should I also make lock_guard static because the mutex is static one, as I was told by some coworker of mine.

NO

Consider the scenario where two threads enter your function and both get the same static std::mutex m . One tries to lock it and the other one would not get chance[1]. Furthermore, when the first function exits, it won't actually unlock the mutex since lock_guard is static storage and it's scope is valid here so no destructor will be called.

[1] - std::lock_guard locks in ctor, which would be executed only once if guard is static, second thread would not even try to lock - as corrected by @Slava in comments.

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.

That suggestion is nonsense IMO, and you're righteously confused about it.

The purpose of std::lock_guard is to make locking/unlocking the mutex guaranteed within a particular scope (and robust against exceptions). This is done using the behavior of the destructor function, that is guaranteed to be called when the variables scope is left.
For a static variable the destructor will be at best called at the end of the processes lifetime. Hence the mutex would be locked by the 1st calling thread with the whole process.

The global scope is very unlikely to be correct/make sense, as it would appear with a static lock_guard .

So your colleague is wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM