Is SendMessage or SendMessageTimout thread safe? - windows

I have a very basic question : is SendMessage or SendMessageTimout thread safe ?
SendMessage :
http://msdn.microsoft.com/en-us/library/windows/desktop/ms644950(v=vs.85).aspx
SendMessageTimout
http://msdn.microsoft.com/en-us/library/windows/desktop/ms644952(v=vs.85).aspx
Related:
Sending message from working non-gui thread to the main window

SendMessage and SendMessageTimeout are blocking functions: They pause the sender until the receiver has processed the message and returned. So there is no concurrent access to anything, hence the operation is thread-safe.

Related

The JMS receiver thread and the onMessage() callback

I have looked at similar threads but did not get a satisfactory reply.
In the JMS receiver thread, I see a while loop coded as follows:
while(true)
{
Thread.sleep(1000);
}
The above thread also has a registered listener attached to it, which implements the messageListener interface and thus provides for the the callback onMessage() event.
When the onMessage() event gets triggered on the listener, what happens to the receiver thread?
Does its state become false? Does it get interrupted (and throws an interrupted exception)?
What exactly happens at the while loop stated above?
The code above is simply saying 'wait forever' - it most likely is a hastily designed way of NOT ending this thread before someone hits Ctrl-C. The code of while(true) will always be true, so it just blocks here until this thread is interrupted. There is no magic inside this thread !
However in your second (invisible) 'message dispatcher thread' that has been automatically created in Connection.start() messages are received and dispatched to your onMessage() method. Until you call Connection.stop() or your exit your program.

WaitForSingleObject returning ERROR_IO_PENDING

Does anyone know why WaitForSingleObject() or WaitForMultipleObjects() would return ERROR_IO_PENDING where the object i'm waiting on is an event created with CreateEvent()?
In my testing i've tried WFSO and WFMO, manual and auto, INFINITE and 5000, and as soon as I call WaitFor* I get immediately back ERROR_IO_PENDING.
What on earth can be pending about an event object? The point of them is that you wait on them. This event is not part of an OVERLAPPED and nothing to do with an IO call. It is just being used as a one-shot flag for my worker thread to exit (which is SetEvent()ed by another thread).
So - question is - ERROR_IO_PENDING coming back from WFSO - and ideas?
Rich

Make parent thread wait till child thread finishes in VC

According to MSDN:
The WaitForSingleObject function can wait for the following objects:
Change notification
Console input
Event
Memory resource notification
Mutex
Process
Semaphore
Thread
Waitable timer
Then we can use WaitForSingleObject to make the parent-thread wait for child ones.
int main()
{
HANDLE h_child_thread = CreateThread(0,0, child, 0,0,0); //create a thread in VC
WaitForSingleObject(h_child_thread, INFINITE); //So, parent-thread will wait
return 0;
}
Question
Is there any other way to make parent-thread wait for child ones in VC or Windows?
I don't quite understand the usage of WaitForSingleObject here, does it mean that the thread's handle will be available when the thread terminates?
You can establish communication between threads in multiple ways and the terminating thread may somehow signal its waiting thread. It could be as simple as writing some special value to a shared memory location that the waiting thread can check. But this won't guarantee that the terminating thread has terminated when the waiting thread sees the special value (ordering/race conditions) or that the terminating thread terminates shortly after that (it can just hang or block on something) and it won't guarantee that the special value gets ever set before the terminating thread actually terminates (the thread can crash). WaitForSingleObject (and its companion WaitForMultipleObjects) is a sure way to know of a thread termination when it occurs. Just use it.
The handle will still be available in the sense that its value won't be gone. But it is practically useless after the thread has terminated, except you need this handle to get the thread exit code. And you still need to close the handle in the end. That is unless you're OK with handle/memory leaks.
for the first queation - yes. The method commonly used here is "Join". the usage is language dependant.
In .NET C++ you can use the Thread's Join method. this is from the msdn:
Thread* newThread = new Thread(new ThreadStart(0, Test::Work));
newThread->Start();
if(newThread->Join(waitTime + waitTime))
{
Console::WriteLine(S"New thread terminated.");
}
else
{
Console::WriteLine(S"Join timed out.");
}
Secondly, the thread is terminated when when you are signaled with "WaitForSingleObject" but the handle is still valid (for a terminated thread). So you still need to explicitly close the handle with CloseHandle.

The internal mechanism of GetMessage() in Win32 API?

In the Message Loop of a windows application,the GetMessage() function will suspend the application thread when there is no message in the message queue, but how it manages to wake itself up when a message was enqueued into the message queue? How can a sleeping thread wake itself up?
while (GetMessage (&msg, NULL, 0, 0))
{
TranslateMessage (&msg) ;
DispatchMessage (&msg) ;
}
The thread doesn't wake itself up. The thread that sends it the message wakes it up. Part of the process of sending a message includes waking the recipient of the message.
They wait in the same manner as how a typical asynchronous wait thread waits (using WaitForSingleObject). Internally (in the kernel level), they all wait using a kernel API function called KeWaitForSingleObject

Best way to close and wait for a child frame window using Win32/MFC

There are a few options here, probably, but what would you suggest to be the safest way to accomplish the following:
I've got a child CFrameWnd with a parent = NULL (so that it can live a separate life from the main application, while the app is running, at least). I've got all those windows stored in a list. When the main app is closing (MainFrame getting an OnClose), I go through the array and issue a PostMessage(WM_CLOSE) to all. However, the problem is that each of them has to do stuff before closing down. So, I need to wait for them. But we're all on the same thread... So, how can I wait for the children to close, without blocking their own processing in a single-threaded application?
Or should I launch a worker thread to take care of that? Would it be easier?
Thanks in advance!
Use SendMessage() instead of PostMessage().
Edit: Another option might be to simply handle WM_DESTROY in your child windows (depending on your code of course).
Well you certainly can't just wait for them to close, you need to at least pump messages so that they would receive and handle the WM_CLOSE. How you do that is up to you I guess. But I see you are doing PostMessage. Why not do SendMessage instead - this will run the close synchronously in the window procedure for the window. Or are you trying to quit the app? Then you should really use PostQuitMessage then pump messages in the normal fashion until GetMessage returns 0. Lots of options.
Pumping messages means to have a loop in your code that looks like this. You don't have to call AfxPumpMessages, but that would probably do something similar. There are in fact many different ways to pump messages depending on what you want to do. In addition there are quite a few functions that pump messages for you.
BOOL bRet;
// note that GetMessage returns 0 when WM_QUIT is received - this is how PostQuitMessage
// would work to get us to shut down
// We are passing NULL for the hWnd parameter - this means receive all window and
// thread messages for this thread
while( (bRet = GetMessage( &msg, NULL /* hWnd */, 0, 0 )) != 0)
{
if (bRet == -1)
{
// handle the error and possibly exit
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
If you post the message to a window or windows, then you need to pump messages. What happens is that the message goes into a queue for the thread associated with that window (this thread) - the message pump extracts them out and dispatches them off to the correct window procedure.
If you had sent the message instead of posting it, then the window procedure for the window is called directly - rather than going into a queue. You wouldn't need to pump messages because once SendMessage returns the message is fully handled.
The way PostQuitMessage works is by setting a flag on the message queue indicating that the application should quit. The WM_QUIT message isn't really a window message that you would send - what happens is that GetMessage will check this flag after all the other posted window messages are processed and returns 0 if it is set. This will cause all windows to correctly close, and you don't need to send it to the windows themselves.

Resources