C++: Preventing multiple functions from being exec

2019-07-09 01:53发布

问题:

I ask this questions as all the mutex documentations I find deal with a single function and I think my case is very common.

My question is whether the following code won't only prevent func1() or func2() from being executed multiple times in parallel, but whether it would also prevent func1() and func2() from being executing at the same time?

#include <mutex>

std::mutex my_mutex;

void func1() {
    my_mutex.lock();
    // do something ...
    my_mutex.unlock();
}

void func2() {
    my_mutex.lock();
    // do something ...
    my_mutex.unlock();
}

As I understand many people usually copy code from Stackoverflow, I am adding another version of my sample code, after adding @Al_Bundy's input - using lock_guard, which is destructed when the function ends and thus makes sure your mutex is released when the function ends and the guard is destructed. It is much more safe, as your function could get an exception and your mutex could stay locked when you manually unlock it instead of using lock guard:

#include <mutex>

std::mutex my_mutex;

void func1() {
    std::lock_guard<std::mutex> locker(my_mutex);
    // do something ...
}

void func2() {
    std::lock_guard<std::mutex> locker(my_mutex);
    // do something ...
}

回答1:

Both of your functions are locking the same mutex, therefore at most one of them can be executing at any one time.

Mutexes don't care about functions etc. at all. A mutex itself is either locked or unlocked. Any attempt to lock it while it's already locked will block until the mutex becomes unlocked. You're working with one mutex, so as soon as it's locked by any my_mutex.lock() anywhere in your code, all further calls to my_mutex.lock() will block until my_mutex.unlock() is called.

Once that happens, one of the threads blocking inside the lock() call will unblock, acquire (= lock) the mutex, and proceed. The others will remain blocked.



回答2:

yes, as long as the same mutex is locked, it can't be locked from anywhere else until it is unlocked.



回答3:

Yes, in most of case this is true. But pay attention that mutexes have a thead owner. As long as it is the same thread the lock() will not wait for the mutex to be released.



标签: c++ mutex