Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Preventing multiple functions from being executed at the same time

Tags:

c++

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.

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 safer and better practice, as it releases the mutex in any case the function returns or exits, even when it exits because of an exception.

#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 ...
}
like image 307
SomethingSomething Avatar asked Feb 05 '23 21:02

SomethingSomething


1 Answers

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

like image 71
xander Avatar answered Feb 09 '23 00:02

xander