views:

175

answers:

4

Is there any way to find out from threadId , if a thread has message queue or not?

Basically there are some windows api which only work if a thread has message queue.window

A: 

You could try using AttachThreadInput from a thread which DOES have a message queue. I believe AttachThreadInput fails if either thread referenced in the call does not have a queue. Note that AttachThreadInput can fail for other reasons though.

Bob Moore
+2  A: 

You can use PostThreadMessage with the ID of the thread. If PostThreadMessage returns false and GetLastError returns ERROR_INVALID_THREAD_ID, the thread ID is invalid or the thread does not have a message queue.

More information http://msdn.microsoft.com/en-us/library/ms644946(VS.85).aspx

jrbjazz
-1, there's a bit of a race condition here.
MSalters
@MSalters. From MSDN: "The thread to which the message is posted must have created a message queue, or else the call to PostThreadMessage fails". So for me is a good way to know if the target thread has a message queue. What race condition do you see?
jrbjazz
+1  A: 

In a multi-threaded world, you can't properly account for things that can change while you're looking. Thread message queues are particularly funny; they are created when the thread needs them. So the only answer you could get is "not when I last checked".

As a result, most Windows API's won't actually fail if there's no thread message queue. They simply create it. There is one exception, PostThreadMessage. That would need to create a thread message queue for another thread, potentially at the same time as that other thread is creating its own. Hence, it is the only API that can fail.

But is it bad that PostThreadMessage fails? That tells you (via `GetLastError()) that the queue didn't exist at the one moment when it mattered, when Windows tries to deliver your message.

MSalters
A: 

I think IsGUIThread is the needed function

Nedko