Multithreading — is it safe to call multiple threads of DLL function in a single application?

I write a server application in Delphi 2009 to realize several types of authentication Each authentication method is stored in a separate DLL Use the verification method for the first time and load the corresponding DLL The DLL is released only when the application is closed

Is it safe to access DLL without any form of synchronization between server threads (connections)?

Solution

Short answer:

Yes, you can usually call DLL functions from multiple threads, because each thread has its own stack, and calling a DLL function is more or less the same as calling other functions of other code

Long answer:

If possible, it actually depends on using DLL functions that share variable states

For example, if you do this:

DLL_SetUser(UserName,Password)
if DLL_IsAuthenticated then
begin
...
end;

Then it is absolutely unsafe to use from different threads In this example, you can't guarantee in DLL_ Setuser and DLL_ There is no other thread pair DLL between isauthenticated_ Setuser makes different calls

However, if the DLL function does not depend on a predefined state, that is, all necessary parameters can be used at once, and all other configurations are the same for all threads, you can assume that it works

if DLL_IsAuthenticated(UserName,Password) then
begin
...
end;

But be careful: DLL functions may look atomic, but they are not used internally For example, if a DLL creates a temporary file that always has the same name, or accesses a database that can only process one request at a time, it will be considered shared (sorry, I can't think of a better example)

Summary:

If DLL manufacturers say their DLLs are thread safe, I will use them from multiple threads without locking If they are not - or even if the supplier does not know - you should use the lock safely

At least before encountering performance problems In this case, you can try to create multiple applications / processes that contain your DLL calls and use them as proxies

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>