I understand I can use a mutex member in a class and lock it inside each method to prevent data race in multithreading environment. However, such method might incur deadlock if there are nested calls in the class's methods, like the add_one() and add_two() in below class. Using different mutex for each method is a workaround. But are there more principled and elegant way to prevent deadlock in the case of nested calls?
class AddClass {
public:
AddClass& operator=(AddClass const&) = delete; // disable copy-assignment constructor
AddClass(int val) : base(val) {}
int add_one() { return ++base; }
int add_two() {
add_one;
add_one;
return base;
}
private:
int base;
};