Delphi DLL - thread safe

I have a Delphi DLL and I want to load it in my application inside a stream (more than one, to be exact). The DLL simply creates the object, then it uses it and destroys it. From this point of view, the DLL code is thread safe.

But what happens if I load this dll into a stream? Is the DLL still a safe thread? What do I know about loading DLL files? I saw that VCL has the IsMultThread property that was set when the thread was created, but will the DLL receive a notification about this or should I do it manually?

+6
source share
3 answers

The most common mistake is the use of global variables. If you do not use any global variables (or correctly synchronize access to those that you use), you have a long way to ensure thread safety.

IsMultiThread used, for example, by the memory manager for optimization in a single-threaded case. Personally, I do not think that this is a worthwhile optimization these days, since almost all useful code has streams of some description. I would just set IsMultiThread to True at the beginning of your DLL, for example. in the begin / end block of your .dpr DLL file or in one of the initialization sections of your device, which is equivalent.

To answer your question directly, an instance of IsMultiThread in your DLL will not be set true unless you create a thread in this DLL. Since you create streams in EXE, you need to do it yourself in the DLL.

More generally, it is simply not possible to talk a lot about the thread safety of your code without knowing what it does and what you really mean by thread safety. The latter may seem strange, but I mean the question discussed in Eric Lippert, the famous What is this thing that you call "thread safe"? article.

+11
source

Set IsMultiThread to True first thing that is in the main block of your library project:

 library MyLibrary; begin IsMultiThread := True; ... end. 

This will instruct the memory manager to use thread-safe allocation / deallocation procedures.

+4
source

If you are careful about what you do in the stream, you will be fine. If you need to update the VCL of the main thread, use synchronization or, better yet, do not.

I have a big DLL where I do a lot of database access and it works in a thread. Everything was great in my unit tests, but it blew the sky high when launched in a thread in the main application. Turns out I had to reread the thread safety database documents. In my case, this is DBISAM, and I just had to create a new session for an instance with a streaming database so that it would not collide with the main one.

Another place where I ran into difficulties (again, did a great job with unit tests, did not go through threads) is related to XML processing. I had to call CoInitialize / CoUnInitialize before / after using the XML DOM. This is true for any SOAP material that uses the XML DOM under the hood.

+2
source

Source: https://habr.com/ru/post/885988/


All Articles