Reputation: 31
I have a class Processor that can be notified of objects. The notified objects are eventually processed in a separate thread.
Since the queue is shared between different threads, it needs a mutex q_mutex
to prevent erroneous behavior.
class Processor {
std::queue<int> q;
void q_processing_thread(); // while true loop - uses the mutex
public:
void notify(int); // pushes int to q - uses the mutex
bool isEmpty() const; // checks if the queue is empty - uses the mutex
};
The question:
Should the mutex be an attribute of Processor or a global variable ?
Conceptually,
isEmpty
should be const
since it shouldn't be altering the object. However that prevents it from
locking the mutex.Upvotes: 0
Views: 782
Reputation: 27115
A mutex should be declared with the same scope and extent as the data that it protects. The only data in your example, is the member variable q
. So, assuming that q
is what you want to protect, then a mutex that is intended to protect q
probably should be a member of the same class.
Upvotes: 0
Reputation: 631
Global variables are generally frowned upon.
Since C++ does not have an owning mutex it is best to just have it be a member attribute
mutable allows it to be mutated even if your this
is const
class Processor {
std::queue<int> q;
mutable std::mutex mtx;
void q_processing_thread(); // while true loop - uses the mutex
public:
void notify(int); // pushes int to q - uses the mutex
bool isEmpty() const; // checks if the queue is empty - uses the mutex
};
Lock as soon as you need the mutex, preferably through std::lock_guard or scoped_lock.
Do not keep it locked any more time than nessecary as this can cause performance issues
Upvotes: 1