Mutex on part of class

1k Views Asked by At

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.

3

There are 3 best solutions below

4
On BEST ANSWER

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).

0
On

Yes, it is possible. Only catch is that it will be object specific. You should not be locking a mutext and waiting for another, which can lead to deadlock situation.

0
On

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.