jeudi 18 août 2016

Thread-safe function call: std::mutex inside a std::shared_ptr

I have an application that makes a number of calls to an external library. One of these calls is not thread-safe so everything will crash if I don't guard it somehow.

I tried to use the following pattern, i.e. wrapping a mutex inside a shared_ptr. Note that this class may be instantiated at many different places in the application from different threads.

class MyClass 
{
public:
    MyClass(const std::shared_ptr<std::mutex>& mutex) :
        _mutex(mutex)
    {
    }

    MyClass(MyClass&& other) :
        _mutex(other._mutex)
    {
    }

    void run()
    {
        std::lock_guard<std::mutex> lock(*_mutex);

        ExtLib::runNonThreadSafeFunction();
    }
private:
    std::shared_ptr<std::mutex> _mutex;
};

Are there any risks using this approach? I'm suspecting that it causes dead-locks but I'm not sure.

If this is not a good approach, how would you implement it?

(I am also considering using a static mutex inside the run-function, but I believe vs2013 doesn't support it: http://ift.tt/2bkWgDD).

Aucun commentaire:

Enregistrer un commentaire