Comparing thread handles
I have a simple scenario where a service thread calls some callbacks. One of
the things I must avoid is that the callback tries to turn off the service
thread because this then leads to a WaitForSingleObject(service_thread)
which of course never works, the thread is blocked waiting for itself to
Now, what I thought was that I'd check that I'm not running in the context
of the service thread:
assert( service_thread != GetCurrentThread());
However, this won't work because GetCurrentThread() returns a "pseudo
handle" that is just a symbolic alias for the current thread's handle. If
anyone could tell me how to perhaps fix the comparison above, I would be
happy, too, but there's one more attempt I made:
assert( GetThreadId(service_thread) != GetCurrentThreadId());
Alas, while this might have worked, GetThreadId() requires MS Windows Vista,
Longhorn or Server 2003. Okay, I thought, we'll have to take the
HANDLE h = OpenThread( THREAD_ALL_ACCESS, FALSE, GetCurrentThreadId());
Three more lines than I wanted, but this method must be bullet proof. Well,
in case you didn't guess it already, it isn't. Even though I got two
handles referring to the same thread, those handles had different values
and we're back at step 1 (i.e. how to implement the comparison properly).
Of course, my last way out would be to store the thread ID along with the
waitable handle and compare that when shutting down, but I don't need the
ID otherwise and I don't want to waste that storage without need.
Any better ideas anyone?