问题描述
我问这个问题,因为我发现所有 mutex 文档都涉及一个功能,我认为我的情况很普遍.
I ask this questions as all the mutex documentations I find deal with a single function and I think my case is very common.
我的问题是,以下代码是否不仅会阻止func1()
或func2()
并行执行多次,而且还会阻止func1()
和func2()
同时执行?
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();
}
据我了解,许多人通常是从Stackoverflow复制代码,因此在添加@Al_Bundy的输入后,我将添加示例代码的另一个版本-使用lock_guard,该函数在函数结束时会被破坏,从而确保在功能结束,防护罩被破坏.这样更加安全,因为当您手动解锁而不使用锁保护功能时,您的函数可能会发生异常,并且互斥锁将保持锁定状态:
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 ...
}
推荐答案
您的两个函数都锁定同一个互斥锁,因此最多只能在任何一次执行它们.
Both of your functions are locking the same mutex, therefore at most one of them can be executing at any one time.
Mutexes根本不关心功能等.互斥锁本身是锁定的或未锁定的.在互斥锁已解锁之前,任何试图锁定已锁定的尝试都将阻止.您正在使用一个互斥锁,因此一旦它被代码中任何my_mutex.lock()
锁定,则对my_mutex.lock()
的所有后续调用都将阻塞,直到调用my_mutex.unlock()
为止.
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.
一旦发生这种情况,在lock()
调用内阻塞的一个线程将解除阻塞,获取(=锁定)互斥锁,然后继续.其他人将保持封锁状态.
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.
这篇关于C ++:防止同时执行多个功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!