Singleton - multithreaded issue in C++ [duplicate] - c++

This question already has answers here:
Is Meyers' implementation of the Singleton pattern thread safe?
(6 answers)
Closed 6 years ago.
I've seen posts about this issue but I'm still trying to figure it out. Is this way alright for implementing a safe singelton? I'm using mutex, static member and return its reference.
#include <mutex>
using namespace std;
mutex mtx;
class MySingleton {
private:
MySingleton();
public:
MySingleton& getInstance() {
mtx.lock();
static MySingleton instance;
mtx.unlock();
return instance;
}
};

Is this way alright for implementing a safe singelton?
It's overshoot. Just get rid of the mutex and write:
static MySingleton& getInstance() {
static MySingleton instance;
return instance;
}
The thread safe creation of instance is guaranteed when the function is called the 1st time.

Related

Differences between Singleton and global variable [duplicate]

This question already has answers here:
C++ singleton vs. global static object
(8 answers)
Closed 5 years ago.
I know that singleton allow only one instance of an object. Each method declared in the singleton will only operate on this object.
I was wondering why to not simply declare a global object which will achieve the same goal?
I am certainly forgetting something. If singletons exist there must be specific uses or help to realize specific mechanisms.
For instance:
class Singleton
{
public:
static Singleton& Instance()
{
static Singleton sg;
return sg;
}
void function();
};
would be the same as:
class NotSingleton
{
public:
NotSingleon();
~NotSingleton()
void function();
};
NotSingleton nsg;
However, nothing prevent me to use more than one instance of NotSingleton
Singleton is used when we do not want to create more than one object. Singleton class ensures that not more than one object is created. However, having a global object doesn't ensure this.
class Singleton {
public static Singleton object = null;
public void singleton() {
if (object == null)
object = new Singleton();
return object;
}
}
This class will not create more than one object. This is the purpose of the Singleton class.

Limiting mutex scope using blocks in header [duplicate]

This question already has answers here:
Mutex example / tutorial? [closed]
(7 answers)
Closed 6 years ago.
I have a class that has its own worker thread, and some of the member variables of the class is shared between the main thread and the worker. How can I use a mutex to lock only the member variables that are being shared?
For instance, this does not work (since the block scope is outside any function).
class Foo {
public:
// Some stuff
private:
boost::thread *m_worker;
Bar m_bar_nonshared;
{
boost::mutex m_mutex;
Bar m_bar_shared;
}
};
A mutex doesn't lock member variables, it locks code. The only way for it to lock a member variable is if it locks the only code that accesses it.
That is, put the lock in the access functions (get/set) and don't allow access to the members any other way.

Why undefined referenced to mMutex in my singleton class [duplicate]

This question already has answers here:
Undefined reference to static class member
(9 answers)
Closed 8 years ago.
I have implemented a Meyer's singleton pattern. And I try to do some stuff testing it in a multithreading environment. Here is how I implemented the class in C++.
#include<thread>
#include<mutex>
class singleton {
public:
static singleton& instance() {
std::lock_guard<std::mutex> lck(mtx);
static singleton *my = new singleton;
return *my;
}
private:
static std::mutex mtx;
singleton() {}
~singleton() {}
singleton(const singleton &) {}
singleton& operator=(const singleton &) {}
};
But when I compile this with g++ -std=c++11 singleton.cpp -o singleton -lpthread, it says
/tmp/ccfEBnmN.o: In function `singleton::instance()':
singleton.cpp(.text._ZN11singleton12instanceEv[_ZN11singelton12instanceEv]+0x10):
undefined reference to `singleton::mtx' collect2: error: ld returned 1 exit status
I understand this might be some problem in design, since without initializing the first singleton instance how could we get the mtx. If in this case, my question comes to how to implement a thread safe singleton class based on my code? How do we initialized the mtx in my singleton class?
I know there is a traditional way to create a singleton pattern by maintaining a static pointer points to the singleton class. But indeed that is not "so" thread safe. Even applying the double check mechanism in the instance() method.
You've declared mtx in singleton, but failed to define it, which has to be outside of singleton, something like this:
std::mutex singleton::mtx;
This should be in a source file, not a header though (otherwise you'll get multiple definition errors when/if you include the header in more than one source file).
Second point: what you're showing is not a Meyer's singleton pattern at all. For a Meyer's singleton, you define a static instance of the singleton inside the function:
static singleton &instance() {
static singleton my;
return my;
}
Using this, it's not clear that you really need a mutex at all.
Your static data member mtx needs a definition. Place this in your source file:
std::mutex singleton::mtx;
More accurately, std::lock_guard<std::mutex> lck(mtx) odr-uses mtx so its definition is required. You get a link-time error when the linker cannot resolve the reference.
Also note that in C++11 the initialization of an object with static storage duration is thread safe, you don't need a mutex.

memory allocation for static singleton class object [duplicate]

This question already has answers here:
Where are static variables stored in C and C++?
(16 answers)
Closed 9 years ago.
For below singleton class where would be the memory taken from (Stack or Global memroy)
class Singleton
{
public:
static Singleton* get()
{
static Singleton instance;
return &instance;
}
};
instance will be located in static storage (or global as you call it).

using std::shared_ptr with a protected constructor\destructor [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I call ::std::make_shared on a class with only protected or private constructors?
I want to create a shared pointer to a class, and have a factory method that returns it while keeping the constructor\destructor protected. since the shared pointer can't access the the constructor or the destructor, I get compiler errors.
I am using llvm 4.1, but I am looking for a solution that can be compiler independent (besides making the constructor\destructor public).
this is a code sample:
class Foo
{
public:
static std::shared_ptr<Foo> getSharedPointer()
{
return std::make_shared<Foo>();
}
protected:
Foo(int x){}
~Foo(){}
};
any Ideas?
Just allocate the pointer yourself instead of calling make_shared:
static std::shared_ptr<Foo> getSharedPointer()
{
return std::shared_ptr<Foo>(new Foo);
}
Note, however, that this would require making the destructor public.