LoadLibrary Static/Globals and Threads - windows

Say I have a DLL that has the following static/global:
ClassA Object;
Along with the implementation of ClassA, it also contains a 'regular' ClassB, which will not work properly if ClassA has not been constructed yet (which is why I've made ClassA is a static/global).
In Windows, I believe that the DLL loader will load this DLL on the call to ClassB's constructor, correct? At this point, ClassA will be constructed and then ClassB's construction will follow. If a second thread comes along and constructs ClassB, ClassA will not be constructed as it has already been constructed.
Now, my question is -- what if ClassB is constructed simultaneously by two threads. So Thread 1 will start to construct ClassA. Will Thread 2 wait until ClassA is completely constructed before executing ClassB's constructor?
In other words, does LoadLibrary() use a CriticalSection to ensure thread-safe initialization of a DLL's static/globals? My hunch is 'yes', but I can't seem to find any documentation saying one way or the other.

DllMain is called by the Windows loader while holding an internal critical section known as the "loader lock," so your static constructors will be called during the DLL_PROCESS_ATTACH event, which only occurs once, when your DLL is first loaded.

Look at the documentation for DllMain; I believe it talks about the loader lock and initialization order.

DLL's are not initialized like EXE's since they are shared by multiple processes. What you need is effectively a singleton object that is a one time factory for your other objects.
Note, I'm assuming here by "ClassA" and "ClassB" you mean instances of those classes...
For example you could have a someting like
ClassA& GetTheClassAInstance();
ClassB& GetTheClassBInstsance();
The first time these are called, these functions would ensure that your global instances of ClassA and ClassB were properly constructed.

Related

Purpose of instantiation of Service classes

I have repeatedly seen a Ruby pattern of initializing objects of Service classes, i.e. classes that have a singular "call" instance method and nothing else.
For example in the dry-validation gem (https://dry-rb.org/gems/dry-validation/1.8/schemas/) the contract class is initialized, then that instance is used for validation and never used again.
Same with other Service classes, I found multiple tutorials where it is used like ServiceClass.new(stuff).call().
I don't understand why to jump through the additional hoop of object initialization, when you can achieve the same behavior by simply defining a class method that does the job, like ContractClass.call(example: "hi") and ServiceClass.call(stuff) respectively.
Am I missing something here? Repeatedly initializing one-of objects seems completely pointless to me.

C++11 Singleton. Static variable is thread safe? Why?

I just read, that this construct:
const bg::AppSettings& bg::AppSettings::GetInstance()
{
static AppSettings instance;
return instance;
}
is a thread safe and working way to create a singleton?! Am I correct, that the static AppSettings variable will be the same, every time I call this method?! I get a little bit confused about the scoping on this one ...
My normal approach was to use a unique_ptr as a static member of my class ... but this seems to work...can someone explain to me, what's going on here?!
And btw.: does the const make sense here?!
In C++11 (and forward), the construction of the function local static AppSettings is guaranteed to be thread-safe. Note: Visual Studio did not implement this aspect of C++11 until VS-2015.
The compiler will lay down a hidden flag along side of AppSettings that indicates whether it is:
Not constructed.
Being constructed.
Is constructed.
The first thread through will find the flag set to "not constructed" and attempt to construct the object. Upon successful construction the flag will be set to "is constructed". If another thread comes along and finds the flag set to "being constructed", it will wait until the flag is set to "is constructed".
If the construction fails with an exception, the flag will be set to "not constructed", and construction will be retried on the next pass through (either on the same thread or a different thread).
The object instance will remain constructed for the remainder of your program, until main() returns, at which time instance will be destructed.
Every time any thread of execution passes through AppSettings::GetInstance(), it will reference the exact same object.
In C++98/03, the construction was not guaranteed to be thread safe.
If the constructor of AppSettings recursively enters AppSettings::GetInstance(), the behavior is undefined.
If the compiler can see how to construct instance "at compile time", it is allowed to.
If AppSettings has a constexpr constructor (the one used to construct instance), and the instance is qualified with constexpr, the compiler is required to construct instance at compile time. If instance is constructed at compile time, the "not-constructed/constructed" flag will be optimized away.
The behavior of your code is similar to this:
namespace {
std::atomic_flag initialized = ATOMIC_FLAG_INIT;
std::experimental::optional<bg::AppSettings> optional_instance;
}
const bg::AppSettings& bg::AppSettings::GetInstance()
{
if (!initialized.test_and_set()) {
optional_instance.emplace();
}
return *optional_instance;
}
By having a thread-safe flag that lives for the entire duration of the program, the compiler can check this flag each time the function is called and only initialize your variable once. A real implementation can use other mechanisms to get this same effect though.

Resharper refactoring creating static methods

When you refactor a method using Resharper 8 and the method arguments do not depend on instance variables of the class, a static method is constructed. However, an instance method could also have been created.
Is a static method created for performance reasons?
TIA.
That's right. Here’s what the MSDN documentation has to say about it:
Members that do not access instance data or call instance methods can
be marked as static (Shared in Visual Basic). After you mark the
methods as static, the compiler will emit nonvirtual call sites to
these members. Emitting nonvirtual call sites will prevent a check at
runtime for each call that makes sure that the current object pointer
is non-null. This can achieve a measurable performance gain for
performance-sensitive code. In some cases, the failure to access the
current object instance represents a correctness issue.
Source: http://msdn.microsoft.com/en-us/library/ms245046.aspx

Performance gain of marking class methods as static

I am using FxCop to look for improvements on our application. One of the rules we are often breaking is "Mark members as static" which is marked as a performance rule.
Certainly we have a lot of class methods that do not action on any of the class members, which could be marked as static, but is there really a performance gain to this?
My understanding is that static will be intantiated once at execution time. If the method is never invoked that it would have been a waste. If the method is invoked multiple times than there might be a small benefit.
With variables there are obvious implications as to whether or not they are marked static, and it is critical to the operation of your application how they are defined. For methods though I don't believe there is any functional affect on whether or not they are marked static if they do not reference any instance variables or methods.
Am I missing the point here? Is the standard to mark all of these methods as static?
Performance becomes better because static method doesn't have hidden "this" pointer.
Every instance (non-static) method has hidden "this" pointer, which is passed to the method to access instance members. If no non-static members are used, "this" pointer remains unused. Passing additional parameter on the stack or in CPU register takes a time which can be saved by declaring such method as static.
"My understanding is that static will be instantiated once at execution time."
Both static and non-static methods exist only once in the program code. Only non-staic data members are duplicated, when there are different class instances. Non-static class method works with specific instance using class reference (hidden parameter). Code itself is never duplicated.
As you said, when a method is marked as static, it is instantiated once, the first time it is used. Whenever subsequent calls are made, the runtime environment doesn't need to validate it, because it is guaranteed to exist. Here is the Microsoft doc for it: http://msdn.microsoft.com/en-us/library/ms245046%28v=vs.80%29.aspx
Here's some more guidance: Method can be made static, but should it?

What determines the order of compliation or execution of source file in Delphi Prism?

Having written my Delphi Prism program enough to compile and run on Window and Linux (mono) without compilation errors, I am finding out that my constructors and load events are firing at different order than I expected. I thought, files get executed in the order that they are listed in the project file like in Delphi .dpr file. Speaking of .dpr file, is there a similar file for Delphi Prism that I am not looking into. I looked into program.pas file and properties. I didn't see anything there to give me a hint or clue.
How do you make sure that the project files get executed in right order in Delphi Prism?
Delphi Prism compiles in the order the files are defined in the project. However, there should not be anything that depends on the order of the files as there are no initialization sections.
As for your other question. Program.pas by default contains the entry point, it's a method called "Main", you could see this as the main begin/end.
.NET does not know about the order your classes are listed in your program file. It just sees classes.
Under normal circumstances you could think of this rule:
Static (class) constructors are executed immediately before the instance .ctor or another static (class) method is called on this class for the first time
While this is not true every time (they could be called earlier, but not later), this is a good approximation which works out most of the time.
So to ensure a certain order for static class initialization, I rely on the following:
I have one static class that has an Initialize() method. This method is the first thing I call in the Main() method of my program. In this method I call Initialize-Methods on other classes in the required order. This makes sure, that the initialization code is executed.

Resources