I am following the examples from "Android NDK Game Development Cookbook" for creating a cross-platform thread wrapper for use in my own Android NDK game engine. In the example's Thread class, at a certain point, a check is done to see if a thread handle corresponds to the current thread. This is done as follows:
if ( GetCurrentThread() != FThreadHandle )
The FThreadHandle handle was assigned using the follwing call earlier on:
#if defined(_WIN32)
FThreadHandle = ( uintptr_t )_beginthreadex( NULL, 0, &ThreadStaticEntryPoint, ThreadParam, 0, &ThreadID );
#else
pthread_create( &FThreadHandle, NULL, ThreadStaticEntryPoint, ThreadParam );
#endif
And the getCurrentThread function is defined as follows:
native_thread_handle_t iThread::GetCurrentThread()
{
#if defined( _WIN32)
return GetCurrentThreadId();
#elif defined( ANDROID )
return gettid();
#else
return pthread_self();
#endif
}
My question is: Is this function implementation correct? I have 3 major concerns about this implementation:
I will just comment on the GetCurrentThread
(Win32) part.
It says:
"Retrieves a pseudo handle for the calling thread."
In other words, if you call it from different threads, each thread may receive the same, bogus, handle. Or, in other words, it is possible that the returned value is simply a constant value that is recognized by the Win32 API as a placeholder that represents the current thread.
I'm not sure what needs to be done in order to get a genuine, unique handle for the thread.
I am looking at OpenThread (Win32) function, but I haven't tried it myself.
One thing to remember is that on Windows, "handles" are resources that needs to be cleaned up after use. For each "OpenSomething" function, read the documentation carefully to see if you need to call a "CloseSomething" after use. Also, don't assume that the handle release function to always have the same name as the creation/duplication function. Failure to do so may destabilize the system.
Last but not the least: try search on The Old New Thing.