I have a native Windows DLL written in C. This DLL is designed to be loaded (injected) in different Windos processes. This DLL creates some working threads that look like this:
while(1) {
// do work
Sleep(few secs);
}
The problem is if the process exits and DLL unloads while thread is in Sleep() it will crash the process when it comes back from Sleep (thread will try to execute code that is not there). I was thinking of using TerminateThread() with the DllUnload handler but MSDN says it should be used in most extreme cases only. For example – my threads use critical sections and the documentation says:
If the target thread owns a critical section, the critical section will not be released.
How do I cleanly close the thread that is sleeping when the DLL is unloading? Should I redesign my working threads to do work in some other way?
Create an event:
Use
WaitForSingleObjectinstead ofSleep:Wait for the thread to end itself: