Critical section initialization when creating thread-safe singleton (C++) - c++

I'm trying to do the same thing as suggested in this solution:
How can I create a thread-safe singleton pattern in Windows?
But, where should the critical section be initialized and uninitialized?

Wrap the critical section into a class (use a ready one or craft your own) and declare a global variable of that class - then the critical section will be initialized during the program startup and deinitialized on program exit. Since startup and exit are done on one thread it will work reliably.

Use pthread_once() and you can initialize the critical section before you use it for the first time. Windows has InitOnceExecuteOnce function.

Related

Do I need to DeleteCriticalSection in Destructor?

I'm new to C++ and in my program I have a class that has a private member (CRITICAL_SECTION csPtr).
The InitializeCriticalSection(&csPtr) is called in my constructor.
My question is, do I need to call DeleteCriticalSection(&csPtr) in my destructor?
Yes, according to MSDN:
A critical section object cannot be moved or copied. The process must also not modify the object, but must treat it as logically opaque. Use only the critical section functions to manage critical section objects. When you have finished using the critical section, call the DeleteCriticalSection function.

Is it this safe to do C++ Singleton first instance creation?

To my understanding, if the Singleton::instance() is called in different thread, there might be some problem if both call refer to the first construction of the actual instance.
So if I move the first Singleton::instance() call to the very beginning of the program where no other threads are even created, will this be thread safe now?
Of course, all its member variable are protected by mutex guard when used.
This might open your eyes to a thread-safe Singleton and how easy it isn't.
http://silviuardelean.ro/2012/06/05/few-singleton-approaches/
As per before, it's not very robust if you're requiring it to be created before any threads are kicked off.
Worth noting though, if you compile with C++11, then doing as Brian said (static storage + static method) guarantees thread safety. With any previous versions you will need a mutex, and will run into the caveats mentioned in the link I shared.
So if I move the first Singleton::instance() call to the very beginning of the program where no other threads are even created, will this be thread safe now?
Yes, but this element is not within the Singleton's design and would likely be more robust if it were.
You can often allocate it at file scope or in function scope with static storage within a static method. Verify that your compiler generates exclusion around it or add your own mutex there.
Yes, performing the initial instantiation when you can guarantee there is just one thread extant clearly protects it from other threads causing race conditions.
It doesn't feel terribly robust, though. At the very least, plaster the area with warning comments.
Maybe then you don't need lazy initialization of singleton instance?
If you actually want it then you can protect singleton instance with mutex when you construct it.
Just remember not to put in the header.
If you put the implementation in the header, it may be generated in every compilation unit that uses it. Which means it won't be single.
Also don't compile it in static libraries. This can also lead to multiple instances if the code is linked and merges into several non-static libraries.
If there is no additional thread created yet and you make that move before those threads creation, I don't see a real scenario where you might have problems by using the singleton you already created in any new created multi-threaded environment.
The main thread-safe problem of singleton pattern into a multi-threaded environment is about how to prevent two or more "singleton" instances creation by different threads. I have described this scenario into "Multi-threaded environment" section here.

Using Critical Sections/Semaphores in C++

I recently started using C++ instead of Delphi.
And there are some things that seem to be quite different.
For example I don't know how to initialize variables like Semaphores and CriticalSections.
By now I only know 2 possible ways:
1. Initializing a Critical Section in the constructor is stupid since every instance would be using its own critical section without synchronizing anything, right?
2. Using a global var and initializing it when the form is created seems not to be the perfect solution, as well.
Can anyone tell me how to achieve this?
Just a short explanation for what I need the Critical Section :
I'd like to fill a ListBox from different threads.
The Semaphore :
Different threads are moving the mouse, this shouldn't be interrupted.
Thanks!
Contrary to Delphi, C++ has no concept of unit initialization/finalization (but you already found out about that).
What we are left with is very little. You need to distinguish two things:
where you declare your variable (global, static class member, class member, local to a function, static in a function -- I guess that covers it all)
where you initialize your variable (since you are concerned with a C API you have to call the initialization function yourself)
Fact is, in your case it hardly matters where you declare your variable as long as it is accessible to all the other parts of your program that need it, and the only requirement as to where you should initialize it is: before you actually start using it (which implies, before you start other threads).
In your case I would probably use a singleton pattern. But C++ being what it is, singletons suffer from race condition during their initialization, there is no clean way around that. So, in addition to your singleton, you should ensure that it is correctly created before you start using it in multithreaded context. A simple call to getInstance() at the start of your main() will do the trick (or anywhere else you see fit). As you see, this takes only care of where you declare your variable, not where you initialize it, but unfortunately C++ has important limitations when it comes to multithreading (it is under-specified) so there is no way around that.
To sum it up: just do what you want (as long as it works) and stop worrying.
In my opinion you only need a critical section to synchronize updates to a list box from various threads. Mouse will keep moving. Semaphore is not fitting the solution. You initialize the critical section in you class constructor. where the list box is. Write a method to update the listbox.
//psudo code
UpdateListBox()
{
//enter critical section
//update
//leave critical section
}
All the threads will call this method to update the listbox.
information about critical section is here
http://msdn.microsoft.com/en-us/library/windows/desktop/ms683472%28v=vs.85%29.aspx

Multithreading. Do I need critical sections for read-only access?

I have a bunch of threads. They should access a singleton containing configuration data which is initialized once when the singleton is created. Hence on the first access. So further actions on the singleton are just read-only. Do I need critical sections in this case?
It appears that because the data is created lazily on first access, the pointer or the reference to your singleton is read-write. This means that you do need a critical section.
In fact, the desire to avoid a critical section while keeping the lazy initialization in this situation has been so universally strong that it lead to the creation of the double-checked locking antipattern.
On the other hand, if you were to initialize your singleton eagerly before the reads, you would be able to avoid a critical section for accessing an immutable object through a constant pointer / reference.
I understand your question as there is lazy initialization in your singleton. It is initialized only for the first read.
The next consecutive reads are thread safe. But what about concurrent read during initialization?
If you have situation like this:
SomeConfig& SomeConfig::getInstance()
{
static SomeConfig instance;
return instance;
}
Then it depends on your compiler. According to this post in C++03 it was implementation dependent if this static initialization is thread safe.
For C++11 it is thread safe - see answers to this post, citation:
such a variable is initialized the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. [...] If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.
It is worth to note that read only access to global variables is thread safe.
No. If you're simply reading this data after it is fully initialized and the data never changes then there is no possibility of a race condition occurring.
However, if the data is written to/modified in any way then you will need to synchronize access to it, i.e., lock the data before writing.
If you only ever read some shared data, and never write, you do not need to synchronize access.
You only need to synchronize when a shared piece of data is both read and written at potentially the same time.
The official rule in the spec is that a data race is when one thread can write to a variable concurrently while another thread read or writes the same variable.
If you can prove that the initialization has to take place before any of the readers can read, then you do not need synchronization. This is most often accomplished by initializing before creating (or synchronizing) the threads, or by using static storage variables, which C++11 guarantees some synchronization on

Race condition: One thread creates static object, another thread uses it before it is finished initializing. How to handle?

I have several places in my code where a function static object is created once, and then used (copied) any time that function is called. One of these functions can be called from any thread. The function doesn't access any shared state other than this static object.
When thread 1 calls the function for the first time, the object is created and initialized. However, (by a stroke of luck) I have a repeatable case where the program switches to thread 2 and calls the same function before initialization is finished. The object is assigned, and used, with bad data!
I'm not sure how to handle this. I'm using critical sections in the initialization code, but that's not even the problem. This object is being used before being initialized in the first place.
I tried making this thread local using __declspec(thread), but that doesn't work for objects, apparently.
I could just surround the whole thing with a critical section, and maybe that's the best solution, but I'm concerned about problems like this cropping up in other parts of the code- it'd be nice to have a general solution.
If you are on Windows you could use the InitOnceExecuteOnce API. More details can be found in this Raymond Chen post. Also look at the more generic std::call_once
Couldn't you use a semaphore on the object, setting the semaphore to be already set to 1 when the object is created, and then decrementing it to zero when the object is initialized (and ready for use).
Just need to keep an eye out for resource starvation though.