Windows 8, x64.
Using overlapped Windows sockets Api with IOCP.
Noticed an unexpected behavior with sockets:
For example, a call to DisconnectEx returns an error WSAENOTCONN but later I receive an event in GetQueuedCompletionStatusEx for exactly this disconnect (like it was still scheduled regardless of returned error).
Same happens with AcceptEx (with different error returned, e.g. WSAEINVAL).
I was expecting the IOCP event to be scheduled only for pending operations (returned error code WSA_IO_PENDING), but not other errors.
EDIT: My question is: can IOCP events be scheduled by the system even if calls to DisconnectEx/AcceptEx return an error (WSAGetLastError) that is not WSA_IO_PENDING?
Thank you!
IOCPs tend to flood you with statuses at seemingly odd times, including after you thought the handle was closed... The solution I used for this was to do a PostQueuedCompletionStatus() with a custom OVERLAPPED parameter to indicate "closed for real now" after I had closed the handle. Then any queued system statuses would be processed, and when I got the custom OVERLAPPED I knew I could free all my internal buffers related to the handle.
The answer for the above question is no. The problem I had is I messed up scheduling several IOCP events on the same overlapped structure which resulted in this strange behavior.
Related
I don't understand part of the latest Windows threadpool API. I need help with that.
From the documentation, the recipe to use it for I/O (in my case, for SOCKET) can be summarized as follows:
Call CreateThreadpoolIo.
Call StartThreadpoolIo. You can find this warning there:
You must call this function before initiating each asynchronous I/O operation on the file handle bound to the I/O completion object. Failure to do so will cause the thread pool to ignore an I/O operation when it completes and will cause memory corruption.
Call the operation on the file handle (e.g., WSARecvFrom). If it fails, call CancelThreadpoolIo. Otherwise, process the result when it is available. WSARecvFrom, when used asynchronously, asks for a WSAOVERLAPPED (that you have to create beforehand) but not for any information that links it to the previous call to StartThreadpoolIo. CancelThreadpoolIo only asks for the PTP_IO, but not for any additional information to derive a specific asynchronous operation.
Repeat steps 2 and 3.
Call CloseThreadpoolIo to finish. You can find this warning there:
It may be necessary to cancel threadpool I/O notifications to prevent memory leaks. For more information, see CancelThreadpoolIo.
I usually need it for UDP, so I strive to have several reception operations queued (asynchronous WSARecvFrom operations started) at any given time. That way I don't have to rush to start another reception operation at the beginning of the callback function nor synchronize access to the reception buffers (I can have a pool of them, each one able to contain a datagram, and reissue the reception operation when I finish processing each message; in the interim, other queued operations will keep the receiver busy). Datagrams are independent and self contained. I'm aware that this approach may not be valid for TCP.
StartThreadpoolIo/CancelThreadpoolIo seem to me the source of the problem: StartThreadpoolIo and WSARecvFrom are not directly bound (they don't share any arguments). So:
How can the framework know which operation to cancel when you call CancelThreadpoolIo? How does it cancel just the operation that failed and not any of the pending ones?
You can say, "don't call StartThreadpoolIo concurrently". I can live without several concurrent WSARecvFrom's, but I can't live without concurrent WSARecvFrom and WSASendTo. So I think being unable to have several asynchronous operations at the same time can't be the way the API was designed.
You can say, "call StartThreadpoolIo only once, that will suffice to register the callback; it is an on/off process". But the documentation says:
You must call this function before initiating each asynchronous I/O operation on the file handle...
You can say, "it cancels the operation started by the same thread that just called StartThreadpoolIo". But then the advice of calling CancelThreadpoolIo in the context of calling CloseThreadpoolIo doesn't make sense (I will call CloseThreadpoolIo from the thread that triggers stopping, which will be completely independent from the threads issuing the asynchronous operations; and a single call to CancelThreadpoolIo may not be enough to cancel several operations). Being unable to trigger cancellation from a different thread is a serious limitation, anyway. I'm aware of the existence of CreateThreadpoolCleanupGroup, but my question is more fundamental. I want to understand how this API can be fundamentally right and useful.
You can say "call CreateThreadpoolIo several times, so that you have independent PTP_IO's to work with". It doesn't work. When I call CreateThreadpoolIo a second time, nullptr is returned.
Am I wrong, or is this API awkward? Normally, other asynchronous APIs work with one of these patterns:
Create an operation and receive a handle => call methods passing the handle.
Create a reusable handle => call methods (including starting operations) passing the handle.
The latest Windows threadpool API, in which the handle seems to be implicit, or there are several handles for the same operation (TP_IO, WSAOVERLAPPED, StartThreadpoolIo) and they aren't all explicitly linked together, uses neither of them.
Thank you very much for your help.
How can the framework know which operation to cancel when you call CancelThreadpoolIo? How does it cancel just the operation that failed
and not any of the pending ones?
CancelThreadpoolIo() doesn't cancel IO. It is reciprocal to StartThreadpoolIo(). StartThreadpoolIo() prepares threadpool to accept a completion. If threadpool doesn't expect a completion, it won't wait for it, thus you may miss it. If threadpool expects a completion but completion doesn't happen, threadpool may waste resources.
CancelThreadpoolIo() undoes whatever StartThreadpoolIo() did.
I have a Win32 MFC app that creates a thread which listens on the RS232 port. When new data is received that listener thread allocates memory using new and posts a message to a window using PostMessage. This carries on just fine and the window handles the incoming data and deletes the memory as necessary using delete. I'm noticing some small memory leaks right as my program closes. My suspicion is that one or two final messages are being posted and are still sitting in the message queue at the moment the user shuts the program and the thread closes before that memory gets properly deleted. Is there a way I can insure certain things happen before the program closes? Can I make sure the message queue is empty or at least has processed some of these important messages? I have tried looking at WaitForInputIdle or PeekMessage in destructors and things like that. Any ideas on a good way to solve this?
I 100% agree that all allocated memory should be explicitly free'd. (Just as you should fixed all compiler warnings). This eliminates the diagnostic noise, allowing you to quickly spot real issues.
Building on Harry Johnston's suggestion, I would push all new data into some kind of a queue and simply post a command "check the queue", removing and freeing data in the message handler. That way you can easily free everything left in the queue before exiting.
For a small utility, that leak might be acceptable - but it might cover other causes that are less benign.
PostMessage does not guarantee delivery. So other options are
using a blocking SendMessage
add the data to a deque, use Post Message to notify the receiver new data is available
(Remote code review: if PostMessage returns false, do you delete the memory right away?)
The folks arguing to not worry about it have a valid point. The process is about to end, and the OS will release all the memory, so there's not much point in spending time cleaning up first.
However, this does create noise that might obscure ongoing memory leaks that could become real problems before you application exits. It also means your program would be harder to turn into a library that could be incorporated into another app later.
I'm a fan of writing clean shutdown code, and then, in opt builds, adding an early out to skip the unnecessary work. Thus your debug builds will tell you about real leaks, and your users will get a responsive exit.
To do this cleanly:
You'll need a way for the main thread to tell the listener thread to quit (or at least to stop listening). Otherwise you'll always have a small window of opportunity where the main thread is about the quit just as the listener does another allocation. The main thread will need to know that the listener thread has received and complied with this message. Only then, can the main thread go through the queue to free up all the memory associated with the last messages and know that nothing more will arrive.
Don't use TerminateThread, or you'll end up with additional problems! If the listener thread is waiting on a handle the represents the serial port, then you can make it instead wait on two handle: the serial port handle and the handle of an event. The main thread can raise the event when it wants the listener to quit. The listener thread can raise a different event to signal that it has stopped listening.
When the main thread gets the WM_QUIT, it should raise the event to tell the listener to quit, then wait on the event that says the listener thread is done, then use PeekMessage to pull any messages that the listener posted before it stopped and free the memory associated with them.
When posting a Windows message from a worker thread back to the main thread, our process sporadically receives the "not enough quota" error. Problem is that through extensive tracing we are now quite sure that the main thread's message queue is empty.
This is the configuration:
Regular Windows process, no GUI, hidden main window.
Worker thread creates its own window and message loop.
The two are exchanging messages via PostMessage from time to time. Frequency is in the order of one message per couple of seconds.
I couldn't find any other possible reason for this error in the net than the message queue being filled with 10.000 messages, but as I said, we are quite sure that this is not the case. Are there any other known situations, where this error code can be returned from a PostMessage call?
I wish to launch a separate thread for handling window messages (via a blocking GetMessage loop), but still create the windows in the initial thread, afterward.
Within the separate thread, as soon as it launches, I am calling PeekMessage with PM_NOREMOVE to ensure a message queue exists (is this necessary?), followed by..
AttachThreadInput(initial thread id,GetCurrentThreadId(),true)
..before finally entering the message loop
I am not yet using a mutex or cs to ensure this is happening in time, but am merely using a Sleep statement in my initial thread for the sake of simplicity.
Regardless, window messages do not appear to be intercepted by the separate thread.
I am a little unsure as to whether I am doing this correctly, and would appreciate any possible guidance. Both threads are in the same process
Thank you all
That's not what AttachThreadInput does. Even after you attach your input queue to another thread, Windows still have thread affinity. Messages in the queue for a given window can only be removed from the queue by that window's thread.
What AttachTheadInput does is to make two threads share an input queue. This allows them to query information about the input state and know that the other thread will get the same answer for the same query. For instance, one thread could call GetAsyncKeyState and know that the answer reflected the key state for the other thread.
It allows two or more threads to have the same relationship to the input queue and each other as processes had in Windows 3x. This is the reason that this API exists; so that complex multiprocess applications could be ported from Win 3x to Win95/WinNT.
It seems the best way to instigate window creation from the main thread, while having messages for them handled in a separate, looping thread is to use a custom message, that can be sent to the separate thread - Thus allowing it to create the window, but still allowing that action to be invoked from the initial thread:
1) Allocate a custom message, and create a structure to hold the window initialisation parameters:
message_create_window = WM_USER + 0;
class Message_create_window{
Message_create_window(...);
};
2) Instead of calling CreateWindow(Ex), use something similiar to the following, passing in the relavant window creation parameters:
PostThreadMessage(
thread.id,
message_create_window,
new Message_create_window(...),
0
);
3) Handle the custom message in the message pump of your ui handling thread, extract the creation parameters, & free afterwards:
MSG msg;
GetMessage(&msg,0,0,0);
...
switch(msg->message){
...
case message_create_window:{
Message_create_window *data=msg->wParam;
CreateWindowEx(data->...);
delete data;
}break;
...
This does, however, have the following side-effects:
The window will be created asynchronously. If it is required that the initial thread block until the window is created (or, indeed, that the window's existence can ever be asserted) then a thread synchronisation tool must be used (such as an event)
Care should be taken when interacting with the window (it is a multithreaded application, after all)
If there are any major holes in this answer, or this seems like a terrible approach, please correct me.
(This is still my question, & I am trying to find the best way to accomplish this)
What happens when you call WaitForSingleObject() on a handle you've created with CreateFile() or _get_osfhandle()?
For reasons not worth explaining I would like to use WaitForSingleObject() to wait on a HANDLE that I've created with _get_osfhandle(fd), where fd comes from a regular call to _open(). Is this possible?
I have tried it in practice, and on some machines it works as expected (the HANDLE is always in the signaled state because you can read more data from it), and on some machines WaitForSingleObject() will block indefinitely if you let it.
The MSDN page for WaitForSingleObject() says that the only supported things that it handles are "change notifications, console input, events, memory resource notifications, mutex, processes, semaphores, threads, and waitable timers."
Additionally, would it be different if I used CreateFile() instead of _get_osfhandle() on a CRT file descriptor?
Don't do it. As you can see, it has undefined behavior.
Even when the behavior is defined, it's defined in such a way as to be relatively not useful unless you don't like writing additional code. It is signaled when any asynchronous I/O operation on that handle completes, which does not generalize to tracking which I/O operation finished.
Why are you trying to wait on a file handle? Clearly the intent matters when you are doing something that isn't even supported well enough to not block indefinitely.
I found the following links. The concensus seems to me, don't do it.
Asynch IO explorer
Waiting on a file handle
When an I/O operation is started on an
asynchronous handle, the handle goes
into a non-signaled state. Therefore,
when used in the context of a
WaitForSingleObject or
WaitForMultipleObjects operation, the
file handle will become signaled when
the I/O operation completes. However,
Microsoft actively discourages this
technique; it does not generalize if
there exists more than one pending I/O
operation; the handle would become
signaled if any I/O operation
completed. Therefore, although this
technique is feasible, it is not
considered best practice.
Egghead Cafe:
Use ReadDirectoryChangesW in
overlapped mode. WaitForSingleObject
can wait on the event in the
OVERLAPPED struct.
You can also use the API
WaitForSingleObject() to wait on a
file change if you use the following
change notification function:
FindFirstChangeNotification()
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/fs/findfirstchangenotification.asp
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/waitforsingleobject.asp
An interesting note on "evilness" of ReadDirectoryChangesW:
http://blogs.msdn.com/ericgu/archive/2005/10/07/478396.aspx