Say I have a class A
:
class A {
public:
A();
void fetch_data() { return 1; }
void write_x_data() {
// lock this instance of A
private_function1_which_assumes_locked();
private_function2_which_assumes_locked();
// unlock this instance of A
}
void write_y_data() {
// lock this instance of A
private_function1_which_assumes_locked();
// unlock this instance of A
}
private:
void private_function1_which_assumes_locked();
void private_function2_which_assumes_locked();
};
I want to guarantee that private_function*_which_assumed_locked()
can never be called unless A
is locked.
What's the best way to accomplish this? I've got 5 or so public functions which need locking. These functions never call into each other, so I'm not worried about deadlocking with these. Combined, these 5 public functions call into around 15 different private functions which need to assume the object is in a locked state. Obviously, I can't lock the private functions, since I'd get deadlocks.
Feel free to provide answers in reasonably high-level abstractions, assuming the existences of Mutexes and Scopeguards.
In Python I might do something like this with decorators:
class locked_method(object):
def __init__(self, f):
self.f = f
def __call__(self):
# Do whatever is needed to lock
self.f()
# Do whatever is needed to unlock
class checklocked(object):
def __init__(self, f):
self.f = f
def __call__(self):
# check locked, if not, don't call self.f(),
# and yell at me loudly for screwing up.
self.f()
@locked_method
def func1():
__function_which_assumes_locked()
@checklocked
def __function_which_assumes_locked():
pass
NB: I've not done much in the way of Python, so feel free to comment if my Python is wrong/stupid, but the point of this question is more the best way to accomplish this sort of thing in C++, so hopefully the Python provided is enough to give you an idea of what I want to do.