protoneight
protoneight

Reputation: 31

Mutex for private object - global vs attribute

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,

Upvotes: 0

Views: 782

Answers (3)

Solomon Slow
Solomon Slow

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

JohnkaS
JohnkaS

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

rustyx
rustyx

Reputation: 85361

The mutex should be part of the class.

You can specify it as mutable to make it usable in const methods.

Class Processor {
    std::queue<int> q;
    mutable std::mutex q_mutex;
    . . .
}

Upvotes: 3

Related Questions