This question already has answers here:
How can I determine if a Win32 thread has terminated?
(2 answers)
Closed 6 years ago.
Is there a way to get a notification that a thread no longer runs (has returned) in your application?
I know this is possible in kernel mode (using PsSetCreateThreadNotifyRoutine), but is there a way to know this from user mode, using only Win32 API ?
The problem is that I can't control the code in the thread, because my module is part of a library. Making a driver to monitor the system would not be too hard, but it's annoying for the users to install a driver even for a basic application that uses my library.
My code uses TLS storage, and under Linux/Unix pthread_key_create can take a pointer to a function that is called when the thread is destroyed. But TlsAlloc (Windows) has nothing like this...
Thanks in advance!
Depends on what kind of libraray you have. For a DLL could handle the thread termination in your DllMain (DLL_THREAD_DETACH). The MSDN states that this is the best place to deal with TLS Resources.
Keep in mind that this callback is only calld for a thread exiting cleanly (not by e.g TerminateThread()).
Similar functionality is available with Fibers. From MSDN:
FlsAlloc, FlsCallback, FlsFree
FlsCallback Callback Function
An application-defined function. If
the FLS slot is in use, FlsCallback is
called on fiber deletion, thread exit,
and when an FLS index is freed.
You can simply call WaitForSingleObject on the thread handle.
You could try installing an IAT patching API hook on ExitThread()...
The advantage of this is that you'd get to run in the context of the thread that is exiting which may or may not be useful to you.
See this posting: Windows API spying/hijacking techniques for some details on this kind of hooking...
Related
I would like to have your opinion for this general technical concept. (I am working on microsoft windows OS)
There is a Process, this process creates multiple threads for different tasks.
Main process: it is a windows service written by C# code.
There are several threads that are create inside the main process: Thread_01, Thread_02, ...
Inside Thread_01: There is a Wrapper dll written in managed C++ to consume DLL_01. (DLL_01 is a dll written by me in native C++ code, that provides some APIs: Add, Remove, Connect)
Add and Remove can run very fast, but Connect may take more than 10 seconds and blocks the caller until it finishes.
I am thinking to use std::async to do the Connect function code, and send the result through a callback to the caller (main process).
Is it a good approach? I heard we cannot create or it is better not to create any thread inside inner threads, is it true? If so, how about std::async ?
Any recommendation is appreciated.
Thanks in advance,
None of what you describe makes the use of threads inacceptable for your code.
As usual, threads have issues that need to be cared for:
Data races due to access to shared data.
Problems of ownership of resources is now not just "Who own what?" but "Who and when owns what?".
When a thread is blocked and you want to abort this operation, how do you cancel it without causing issues down the line? In your case, you must avoid calling the callback, when the receiver doesn't exist any more.
Concerning your approach of using a callback, consider std::future<> instead. This takes care of a few of the issues above, though some are only shifted to the caller instead.
I am implementing a function in library which takes a while (up to a minute). It initialize a device. Now generally any long function should run in its own thread and report to main thread when it completes but I am not sure since this function is in library.
My dilemma is this, even if I implement this in a separate thread, another thread in the application has to wait on it. If so why not let the application run this function in that thread anyways?
I could pass queue or mailbox to the library function but I would prefer a simpler mechanism where the library can be used in VB, VC, C# or other windows platforms.
Alternatively I could pass HWND of the window and the library function can post message to it when it completes instead of signaling any event. That seems like most practical approach if I have to implement the function in its own thread. Is this reasonable?
Currently my function prototype is:
void InitDevice(HANDLE hWait)
When initialization is complete than I signal bWait. This works fine but I am not convinced I should use thread anyways when another secondary thread will have to wait on InitDevice. Should I pass HWNDinstead? That way the message will be posted to the primary thread and it will make better sense with multithreading.
In general, when I write library code, I normally try to stay away from creating threads unless it's really necessary. By creating a thread, you're forcing a particular threading model on the application. Perhaps they wish to use it from a very simplistic command-line tool where a single thread is fine. Or they could use it from a GUI tool where things must be multi-threaded.
So, instead, just give the library user understanding that a function call is a long-term blocking call, some callback mechanism to monitor the progress, and finally a way to immediately halt the operation which could be used by a multi-threaded application.
What you do want to claim is being thread safe. Use mutexes to protect data items if there are other functions they can call to affect the operation of the blocking function.
In our application, there is a heavy use of win32 HANDLEs, using CreateEvent, SetEvent/ResetEvent, so as to perform synchronization mechanisms.
A colleague of mine has asked me if accessing the HANDLEs for events was thread-safe.
I could not answer, since HANDLEs are not thread safe for any GDI object...
But since events are aimed towards multithread synchronization, I could not imagine they arent thread safe.
Could you confirm this ?
All handles you obtain from functions in Kernel32 are thread-safe, unless the MSDN Library article for the function explicitly mentions it is not. There's an easy way to tell from your code, such a handle is closed with CloseHandle().
What you do with the handle may not necessarily be thread safe, Windows won't help when you call SetEvent() twice but WaitForSingleObject() only once. Which might be a threading race in your program, depending on how you use the event.
Depends on the type of handle.
A synchronization handle (like one created by CreateEvent) is by definition thread safe.
A file handle, when written to by multiple threads simultaneously, not so much.
When a new window is created using CreateEx does its code execute in its own thread or that of its parent (i.e. the thread in which the its instantiating code was executed)? Thanks.
The window doesn't actually run any code on its own, all the code is called from the message loop which is part of your own code. You can run into huge issues trying to interact with the Windows UI with multiple threads, so you should always respond to the messages within a single thread.
CreateWindowEx() does not create a new thread. If you want a new thread you have to call
either _beginthreadex() (usually preferred) or CreateThread().
In case you're wondering, _beginthreadex() is preferred over CreateThread() because the former initializes parts of the CRT that the latter does not.
Windows have thread affinity – see Raymond Chen's article on this matter.
No, create window dont start new thread
Cross-thread GUI stuff usually ends in disaster. The windows libraries actively discourage it by throwing exceptions.
Even if it was allowed, CreateWindowEx could not do this by default because it would be making some very big assumptions about your code (locks, thread safety, etc); and most Windows development is probably still essentially single threaded.
The boost threading library has an abstraction for thread specific (local) storage. I have skimmed over the source code and it seems that the TSS functionality can be used in an application with any existing thread regardless of weather it was created from boost::thread --i.e., this implies that certain callbacks are registered with the kernel to hook in a callback function that may call the destructor of any TSS objects when the thread or process is going out of scope. I have found these callbacks.
I need to cache HMAC_CTX's from OpenSSL inside the worker threads of various web-servers (see this, detailed, question for what I am trying to do), and as such I do not controll the life-time of the thread -- the web-server does. Therefore I will use the TSS functionality on threads not created by boost::thread.
I just wanted to validate my assumptions before I started implementing the caching logic, are there any flaws in my logic ?
You're right. You can use it for threads not created by boost::thread.
If you look in test_tss.cpp you can see they test exactly that, and it should work with both POSIX and Windows threads.
This is partially right, as the destructor is not called when the main thread finish.