Singleton class for mutex in c++

c++, c++11, multithreading, mutex

Solution

You don't need so much boilerplate. You just need a function:

std::mutex& getCommonMutex() {
    static std::mutex m;
    return m;
}

That's all, you can call this function from anywhere and it will always return a reference to the same mutex, which will be initialized the first time its called.

Problem

I am struggling to get this working but it seems there is something I don't fully understand. I have a multi-threaded application in a single file (2 classes and the real main in which I create threads and everything). I want to split in 3 files. One for each class (with their headers) and one for main. I have a couple of mutices and a queue to share messages between threads and lock and unlock them at any time. I want to write a singleton class so all of them can share the mutex: header: ``` #ifndef COMMONSINGLETON_H #define COMMONSINGLETON_H #include <mutex> // std::mutex #include <queue> class CommonSingleton{ private: static std::mutex mutex_w_b; //static std::mutex mutex_wifi_ok; //static std::queue <std::string> queue_w_b; public: static CommonSingleton& getInstance(); std::mutex GetMutexWB(); //std::mutex GetMutexWiFiOk(); //std::queue <std::string> GetQueueWB(); private: CommonSingleton() {}; CommonSingleton(CommonSingleton const&); void operator=(CommonSingleton const&); }; #endif ``` And my .cpp file: ``` #include "commonsingleton.h" static CommonSingleton& CommonSingleton::getInstance(){ static CommonSingleton instance; return instance; } std::mutex CommonSingleton::GetMutexWB(){ return mutex_w_b; } /*std::mutex CommonSingleton::GetMutexWiFiOk(){ return mutex_wifi_ok; } std::queue <std::string> CommonSingleton::GetQueueWB(){ return queue_w_b; }*/ ``` In my main I have this to test mutex: ``` CommonSingleton::getInstance().GetMutexWB.lock(); ``` But now I have commented, just to figure out how to compile. This is the error I get: ``` commonsingleton.cpp:4:54: error: cannot declare member function ‘static CommonSingleton& CommonSingleton::getInstance()’ to have static linkage [- fpermissive] static CommonSingleton& CommonSingleton::getInstance(){ ^ commonsingleton.cpp: In member function ‘std::mutex CommonSingleton::GetMutexWB()’: commonsingleton.cpp:9:12: error: use of deleted function ‘std::mutex::mutex(const std::mutex&)’ return mutex_w_b; ^ In file included from commonsingleton.h:5:0, from commonsingleton.cpp:1: /usr/include/c++/4.8/mutex:128:5: error: declared here mutex(const mutex&) = delete; ``` What am I doing wrong right here?

Original source

Related problems