问题
What I actually search for is c++/win32 equivalent for .net ThreadState Enumeration.
Any suggestions?
回答1:
There's very little difference between these, all are waits for different kernel objects.
By "Wait" I assume you mean "I/O wait". "Join" is just "wait for a thread/process". And "Sleep" is "wait for a timer".
To complicate matters more, a thread can be waiting for some combination of kernel objects.
You could find out what objects a thread is waiting for, and the type of those objects, using a kernel debugger. I don't think there's any simpler way.
回答2:
There is no direct equivalent - managed and unmanaged threads should not be considered the same. See here.
An operating-system ThreadId has no fixed relationship to a managed thread, because an unmanaged host can control the relationship between managed and unmanaged threads. Specifically, a sophisticated host can use the Fiber API to schedule many managed threads against the same operating system thread, or to move a managed thread among different operating system threads.
回答3:
The only state of a native thread easily accesible using the winapi is for knowning if the thread has finished its execution. Just use the function WaitForSingleObject()
with the thread handle and a timeout of 0:
DWORD res = WaitForSingleObject(handleThread, 0);
switch (res)
{
case WAIT_OBJECT_0:
printf("The thread has finished\n");
break;
case WAIT_TIMEOUT:
printf("The thread is still running\n");
break;
default:
printf("Unknown error (shouldn't happen)\n");
break;
}
回答4:
The "problem" is that the .NET run time has ownership of your .NET thread. So when you call Abort for example, the run time internals throws a ThreadAbortException exception in the .NET context of your .NET thread, and that's how you can catch it in your thread using catch(ThreadAbortException).
And the same is true with ThreadState, since it has the underlying ownership of your thread, it knows exactly what it's doing and therefore can produce a valid thread state.
Since there is no non-hackins way to officially to query a thread for it's internal state, you could wrap this up in a class. But again, you would entirely depend upon the thread method to adhere to any .Abort()-requests.
来源:https://stackoverflow.com/questions/8185437/how-to-determine-that-a-win32-thread-is-either-in-wait-or-join-or-sleep-state-in