Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if Multiple threads in one application call a single DLL

Tags:

c++

c#

dll

I wanted to know what happens when three threads in one application call a static method from DLL (almost) simultaneously. Are there 3 instances of the DLL loaded for each thread or does the other threads only get access to the DLL once the first thread is done with the DLL static method (i.e) each thread gets access to the dll once its turn comes up ?

like image 492
Rajeshwar Avatar asked Feb 26 '13 23:02

Rajeshwar


3 Answers

Are there 3 instances of the DLL loaded, one for each thread?

No. DLLs are usually loaded once per process. (There are some subtle issues here; it is possible for the same assembly to be loaded twice if you use Load and LoadFrom. But this is a rare case, and has nothing to do with threading.)

Do the second and third threads only get access to the DLL once the first thread is done with the DLL static method?

No; static methods are not automatically serialized. If you need the method to ensure that only one thread accesses it at a time then you're going to have to write the code to do that yourself.

Static constructors do behave a bit like that though. The runtime will ensure that the thread which "wins the race" will run the static constructor. The other threads will wait for the first thread to complete the cctor. Read my recent series of articles on that for details.

http://ericlippert.com/tag/static-constructors/

like image 74
Eric Lippert Avatar answered Oct 19 '22 23:10

Eric Lippert


In general, code gets loaded once, even for non-static objects.

It's the information that is contained in declared variables (collectively called state) that you have to worry about, not code.

like image 30
Robert Harvey Avatar answered Oct 20 '22 00:10

Robert Harvey


DLL get loaded in memory only once.

If there are multiple threads within the same process making calls or accessing globals within the DLL, the DLL has to guarantee thread safety by protecting access to global/shared data using critical sections.

If there are multiple threads from multiple processes accessing the DLL, thread safety is not an issue as long as there is not more than one thread from the process accessing the same DLL.

The operating system cleverly manages memory such that initially it starts with only one copy of the code and data sections. The data section pages are mapped read-only. When there comes a need that any global data gets modified in one of the processes, the OS would get a segmentation fault and create a copy of the page and map it as writeable in the process's memory space. This approach is called copy-on-write.

like image 35
Tuxdude Avatar answered Oct 20 '22 00:10

Tuxdude