AlexandruC
AlexandruC

Reputation: 3637

Wait for threads from loaded dll to finish in windows

I have a thread that runs in a dll that I dynamic link with in my main app. Is there a way to wait for all threads in an .exe (including it's loaded dll's) without knowing the thread handle? Windows 7 x64, vc++ The thread is a function that does some processing on a certain file, it is not expected to return anything, it works upon a global class that is modified in certain stages of the thread completion. The thread function calls upon other functions . I want to wait until the last line of the function is executed.

Upvotes: 0

Views: 1397

Answers (2)

Harry Johnston
Harry Johnston

Reputation: 36328

Another solution, assuming that all you want is to stop the main() function from running but not exit the process until any other threads are complete, is to call

ExitThread(GetCurrentThread());

from within main(). If you don't call ExitProcess, either explicitly or by returning from main(), Windows will not exit until the last thread exits.

Note that there is a major problem with doing this, no matter how you approach it: if one of the Windows APIs you use has launched a thread that isn't going to exit, your application won't exit either.

The proper solution is for the DLL itself to contain a shutdown function that waits for its own threads to exit if necessary.

Upvotes: 1

Frerich Raabe
Frerich Raabe

Reputation: 94409

I never did this myself, but you could probably

  1. create a snapshot using CreateToolhelp32Snapshot
  2. then enumerate the threads using Thread32First and Thread32Next
  3. for each thread ID, use OpenThread to aquire a handle. Make sure that you open the thread with the SYNCHRONIZE privilege so that you can, at last
  4. pass all thread handles to WaitForMultipleObjects to wait for all of them to terminate.

Upvotes: 2

Related Questions