[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 142
  • Last Modified:

Thread and dll question

I have a small program that uses threads - if i load in a dll with functions that the threads will use, will a dll be loaded in for each thread or will only one dll be loaded and the threads share access to it?  Also, if two or more threads need to access the dll, should i ensure the dll is thread safe or is each thread able to access the dll as if the thread was a different program?
0
gshep
Asked:
gshep
  • 2
3 Solutions
 
Russell LibbySoftware Engineer, Advisory Commented:
Regarding your questions....

1.) A dll is loaded only once per process, not per thread. Additional "loads" only increment the ref count on the dll. (You can code the DLLMain entry point to test this, eg)

-------------
library Project1;

uses
  Windows;

procedure DLLMain(Reason: Integer);
begin

  // Handle calling based on reason code
  case Reason of
     DLL_PROCESS_DETACH   :  ; // Check count of detatch
     DLL_PROCESS_ATTACH   :  ; // Check count of attach
     DLL_THREAD_ATTACH    :  ;
     DLL_THREAD_DETACH    :  ;
  end;

end;

begin

  // Change the dll proc
  DLLProc:=@DLLMain;

  // Need to call it with process attach
  DLLMain(DLL_PROCESS_ATTACH);

end.
-------------

2.) All process threads will share the dll. If you need to do something specific (like thread local storage, etc), then the DLLmain entry point is a good place for it.

3.) If you want the dll to be thread safe, then you will need to code it as such. Eg, through the use of crtical section/mutex/etc access to shared resources.

---

Hope this helps,
Russell

0
 
MadshiCommented:
Russell is completely right, of course. Just some little extensions:

Local variables are always thread safe. Your dll is automatically thread safe if you're not using any global resources/variables. As soon as multiple threads have (or can potentially have) access to the same variable/resource at the same time, you need to synchronize access to it - using one of the methods Russell mentioned in 3.).
0
 
Lee_NoverCommented:
or use a threadvar - each thread gets it's own copy of the global var :)
but I prefer a proper sync over threadvars anytime
0
 
Russell LibbySoftware Engineer, Advisory Commented:

DanRollins,
Question was answered by all three participants.

By the way...
"thanks" for the work you do, it truly is appreciated.

Regards,
Russell
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now