I am pretty sure these classes are not thread safe.
But, is it safe to use different objects from these classes in different threads?
Do they have any global dependencies with each other like static data or anything to watch out for?
As long as the calls you are making are to static functions that do not access shared memory (shared between threads).
Basically the only time you will hit a problem is if the function you call accesses shared data. If your function simply does some work on data you provide it is thread safe.
Related
I am writing a multithreaded program and have a function that will be called from multiple threads that is a static free function within a cpp file. This function will never be called from outside of the cpp file so I wanted to make it static so that it had internal linkage.
Googling around I found a lot of people saying "static functions are not thread safe" but then when I go to read up about it everyone seems to be talking about static member functions, not static free functions.
Are static free functions thread safe (assuming they don't access any shared state between threads)?
Any function that accesses no shared state is inherently thread safe. You only get a data race when you have unprotected read/writes to shared state. If there is no shared state, you can't have a data race.
This is why purely functional languages are naturally thread safe. If a function doesn't have side effects, then you can call it in as many threads as you want.
Static functions are the same as other functions. It is not the function, it is what the function does.
I think some people are mixing between terms. static function vs function with static variables.
while static function may be safe or not, a function with static variables is not safe without synchronization.
An example of such a function is strtok which keeps in a static variable the continuation point. when several threads use the old strtok, it may cause a mixture between the inputs.
I have created a class, which has many public functions, some which write data and some that only read data.
It's required that I do this within 3 threads, I have no other option.
I know if I accessed a shared resource just to read, then I don't have to protect, but I don't know if it is any different when I am using a function to read a private variable of the shared resource.
E.g. I am trying to do...
globalObject.readColour();
which is a function that reads the colour of the global object.
Does it mean that I have to secure the thread at this point, or is it okay to just read the value without any risks?
I'm working on mbed, which supports c and c++98.
This question is similar to this one
If all your threads will only read the variable then you don't need mutex (or similar), but if any thread performs a writing operation you should use mutex.
In my C++ project I have a singleton class. During project execution, sometimes the same singleton class is accessed from two different thread simultaneously. Resulting in two instances of the singleton class is produced, which is a problem.
How to handle such a cases?
Then it's not a singleton :-)
You'll probably need to show us some code but your basic problem will be with the synchronisation areas.
If done right, there is no way that two threads can create two objects of the class. In fact, the class itself should be the place where the singleton nature is being enforced so that erroneous clients cannot corrupt the intent.
The basic structure will be:
lock mutex
if instance doesn't exist:
instance = new object
unlock mutex
Without something like mutex protection (or critical code section or any other manner in which you can guarantee at the language/library level that two threads can't run the code simultaneously), there's a possibility that thread one may be swapped out between the check and the instantiation, leading to two possible instances of your "singleton".
And, as others will no doubt suggest, singletons may well be a bad idea. I'm not quite in the camp where every use is wrong, the usual problem is that people treat them as "god" objects. They can have their uses but there's often a better way, though I won't presume to tell you you need to change that, since I don't know your use case.
If you get two different instances in different threads you are doing something wrong. Threads, unlike processes, share their memory. So memory allocated in one thread (e.g. for an object instance) is also usable in the other.
If your singleton getting two copies its not guarded with mutex. lock a mutex when getting/accessing/setting the internal object.
I believe You are done something like this if(!_instance)_instance = new Singleton() there lies a critical section. which you need to safe guard with a mutex.
Do not use a singleton, It is a well known Anti-Pattern.
A good read:
Singletons: Solving problems you didn’t know you never had since 1995
If you still want to persist and go ahead with it for reasons known only to you, What you need is a thread safe singleton implementation, something like this:
YourClass* YourClass::getInstance()
{
MutexLocker locker(YourClass::m_mutex);
if(!m_instanceFlag)
{
m_instance = new YourClass();
m_instanceFlag = true;
}
return m_instance;
}
Where MutexLocker is a wrapper class for an normally used Mutex, which locks the mutex when creating its instance and unlocks the mutex the function ends.
I'm using boost singletons (from serialization).
For example, there are some classes which inherit boost::serialization::singleton. Each of them has such define near it's definition (in h-file):
#define appManager ApplicationManager::get_const_instance()
class ApplicationManager: public boost::serialization::singleton<ApplicationManager> { ... };
And I have to call some method from that class each update (nearly 17 ms), for example, 200 times. So the code is like:
for (int i=0; i < 200; ++i)
appManager.get_some_var();
I looked with gprof at function call stack and saw that boost::get_const_instance calls each time. Maybe, in release-mode compiler will optimize this?
My idea is to make some global variable like:
ApplicationManager &handle = ApplicationManager::get_const_instance();
And use handle, so it wouldn't call get_const_instnace each time. Is that right?
Instead of using the Singleton anti-pattern, just a global variable and be done with it. It's more honest.
The main benefit of Singleton is when you want lazy initialization, or more fine grained control over initialization order than a global variable would allow you. It doesn't look like either of these things are a concern for you, so just use a global.
Personally, I think designs with global variables or Singletons are almost certainly broken. But to each h(is/er) own.
If you are bent on using a Singleton, the performance concern you raise is interesting, but likely not an issue as the function call overhead is probably less than 100ns. As was pointed out, you should profile. If it really concerns you a whole lot, store a local reference to the Singleton before the loop:
ApplicationManager &myAppManager = appManager;
for (int i=0; i < 200; ++i)
myAppManager.get_some_var();
BTW, using that #define in that way is a serious mistake. Almost all cases where you use the preprocessor for anything other than conditional compilation based on compile-time flags is probably a poor use. Boost does make extensive use of the pre-processor, but mostly to get around C++ limitations. Do not emulate it.
Lastly, that function is probably doing something important. One of the jobs of a get_instance method for Singletons is to avoid having multiple threads initialize the same Singleton at the same time. With global variables this shouldn't be an issue because they should be initialized before you've started any threads.
Is it really a problem? I mean, does your application really suffers for this behaviour?
I would despise such a solution because, in all effects, you are countering one of the benefits of the Singleton pattern, namely to avoid global variables. If you want to use a global variable, then don't use Singleton at all, right?
Yes, that is certainly a possible solution. I'm not entirely sure what boost is doing with its singleton behind the scenes; you can look that up yourself in the code.
The singleton pattern is just like creating a global object and accessing the global object, in most respects. There are some differences:
1) The singleton object instance is not created until it is first accessed, whereas the global object is created at program startup.
2) Because the singleton object is not created until it is first accessed, it is actually created when the program is running. Thus the singleton instance has access to other fully constructed objects in the program when the constructor is actually running.
3) Because you access the singleton through the getInstance() method (boost's get_const_instance method) there is a little bit of overhead for executing that method call.
So if you're not concerned about when the singleton is actually created, and can live with it being created at program startup, you could just go with a global variable and access that. If you really need the singleton created after the program starts up, then you need the singleton. In that case, you can grab and hold onto a reference to the object returned by get_const_instance() and use that reference.
Something that bit me in the past though you should be aware of. You're actually getting a reference to the object that is owned by the singleton. You don't own that object.
1) Do not write code that would cause the destructor to execute (say, using a shared pointer on the returned reference), or write any other code that could cause the object to end up in a bad state.
2) In a multi-threaded app, take care to correctly lock fields in the object if the object may be used by more than one thread.
3) In a multi-threaded app, make sure that all threads that hold onto references to the object terminate before the program is unloaded. I've seen a case where the singleton's code resides in one DLL library; a thread that holds the reference lives in another DLL library. When the program ends, the thread was still active. The DLL holding the singleton's code was unloaded first; the thread that was still alive tried to do something to the singleton's object and caused a crash.
Singletons have their advantages in situations where you want to control the level of access to something at process or application scope beyond what a global variable could achieve in a more elegant way.
However most singleton objects provided in a library will be designed to ensure some level of thread safety and most likely access to the instance is being locked via a mutex or other critical section of some kind which can affect performance.
In the case of a game or 3d application where performance is key you may want to consider making your own lightweight singleton if thread safety is not a concern and gain some performance.
I have a singleton class, and I will compile it as a library static(lib) or dynamic(dll).
Is it guaranteed that calls to same file in a machine always refer to same and unique instance in both cases?
Edit:
What if a process loads two different library and different functions from these libraries want to use instance of singleton class. Now, they are accessing same instance, am I right?
Thanks,
No, different processes will not share a singleton from a common library. Different processes use different memory spaces, so each will instantiate its own singleton.
You'll need to use some sort of shared memory or interprocess-communication to share data between processes.
If a single process loads libraries A and B, and both those libraries use a singleton from library C, then they will be using the same instance.
You don't call files. You load code into your process from the file, the code contains initialisation instructions that construct your singleton. The singleton is thus unique within your process, regardless of what other code within the process uses it. The singleton is not unique from one process to another, even if they use the same shared library.