What happens if multiple threads in the same application call the same DLL

I wanted to know what would happen when three threads in one application call the static method from the DLL (almost) at the same time. Are there three instances of DLLs loaded for each thread, or do other threads access the DLL only after the first thread is executed using the static DLL method (i.e.), does each thread access the dll after it is rotated?

+4
source share
3 answers

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

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

Does the second and third threads provide access to the DLL only after the first thread is executed using the static DLL method?

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

Static constructors still behave somehow similar. Runtime ensures that a thread that "wins the race" will run a static constructor. The remaining threads will wait for the completion of the first thread. Read my recent series of articles on this subject for details.

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

+9
source

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

This is information contained in declared variables (collectively called states) that you need to worry about, not code.

+3
source

DLL is loaded into memory only once.

If there are several threads in a process that cause calls or access to globals in a DLL, the DLL should guarantee thread safety by protecting access to global / shared data using critical sections.

If there are multiple threads from multiple processes accessing a DLL, thread safety is not a problem if there is no more than one thread from a process accessing the same DLL.

The operating system skillfully manages memory so that initially it starts with just one copy of a section of code and data. The data section pages are read-only. When it becomes necessary to change any global data in one of the processes, the OS will receive a segmentation error and create a copy of the page and display it as being written to the process memory space. This approach is called copy-on-write.

+1
source

All Articles