Is this an acceptable way to lock a container using C++?

Viewed 2956

I need to implement (in C++) a thread safe container in such a way that only one thread is ever able to add or remove items from the container. I have done this kind of thing before by sharing a mutex between threads. This leads to a lot of mutex objects being littered throughout my code and makes things very messy and hard to maintain.

I was wondering if there is a neater and more object oriented way to do this. I thought of the following simple class wrapper around the container (semi-pseudo C++ code)

 class LockedList {
    private:
        std::list<MyClass> m_List;

    public:
        MutexObject Mutex;
 };

so that locking could be done in the following way

 LockedList lockableList;     //create instance
 lockableList.Mutex.Lock();    // Lock object

 ... // search and add or remove items

 lockableList.Mutex.Unlock();   // Unlock object

So my question really is to ask if this is a good approach from a design perspective? I know that allowing public access to members is frowned upon from a design perspective, does the above design have any serious flaws in it. If so is there a better way to implement thread safe container objects?

I have read a lot of books on design and C++ in general but there really does seem to be a shortage of literature regarding multithreaded programming and multithreaded software design.

If the above is a poor approach to solving the problem I have could anyone suggest a way to improve it, or point me towards some information that explains good ways to design classes to be thread safe??? Many thanks.

6 Answers

I came up with this (which I'm sure can be improved to take more than two arguments):

template<class T1, class T2>
class combine : public T1, public T2
{
public:

    /// We always need a virtual destructor.
    virtual ~combine() { }
};

This allows you to do:

    // Combine an std::mutex and std::map<std::string, std::string> into
    // a single instance.
    combine<std::mutex, std::map<std::string, std::string>> mapWithMutex;

    // Lock the map within scope to modify the map in a thread-safe way.
    {
        // Lock the map.
        std::lock_guard<std::mutex> locked(mapWithMutex);

        // Modify the map.
        mapWithMutex["Person 1"] = "Jack";
        mapWithMutex["Person 2"] = "Jill";
    }

If you wish to use an std::recursive_mutex and an std::set, that would also work.

Related