Is it possible to use mutexes on parts of a class ?
Like :
class A{
int a;
int b;
boost::mutex Mutex_for_a;
boost::mutex Mutex_for_b;
}
and then use the right mutex to perform the right operation. I know this is technically possible but I don't know if it can lead to problems.
I know this is technically possible but I don't know if it can lead to problems.
This is certainly possible. However, if not handled carefully, things like this can lead to deadlocks:
A::use_a() { std::lock_guard lck{ Mutex_for_a }; use_b(); ... }
A::use_b() { std::lock_guard lck{ Mutex_for_b }; use_a(); ... }
So you have to make sure that if your class design allows to have both mutexes locked at the same time, the locking order is consistent everwhere (or better use std::scoped_lock
).