Is it possible to use mutex on parts of a class ?
You don't use a mutex on anything. A mutex is a thing that your threads can "lock" and "unlock," and it won't let more than one thread lock it at the same time. That's all. A mutex does not know why your threads lock it. A mutex does not know or care which objects or data your code associates with it.
class A{
int a;
int b;
boost::mutex Mutex_for_a;
boost::mutex Mutex_for_b;
}
That might sense, or it might not. There's no way to tell without seeing how your threads use a
and b
. The main reason for using a mutex is to prevent other threads from seeing some collection of data in an inconsistent or invalid state while some other thread is in the middle of changing it.
If the "collection of data" that you want to protect is contained within a single int
variable, it might make more sense to share it by making it a std::atomic<int>
, and forget about the mutex.
On the other hand, if there is some important relationship between a
and b
, then you should be using a single mutex to protect that relationship.