I read this question I/O Completion Ports *LAST* called callback, or: where it's safe to cleanup things
And i can not get my issue solved. The answer does not fully cover this method. I have also searched a lot here and in google but can not find a solution so i am opening a question here hope that is not duplicated.
In a multi-threaded IO Completion ports design when to increase the RefCount
of the Per Socket structure? ie the CompletionKey
. Currently i do increase it before calling WSARecv
and if the return value of the call is not 0 or ERROR_IO_PENDING
by last error, i decrease it and call a cleanup function, this function will check if the RefCount
is 0, if it is then it will free the Per Socket structure. Else it will just free the Per IO structure (the one of OVERLAPPED), i also increase it before issuing any WSASend
using the same way mentioned above. This RefCount
is atomic using CRITCAL_SECTION
. Upon returning from GetQueuedCompletionStatus
i also decrease the RefCount
.
However i have some questions about this method
I have a function that sends files from the main thread, the function is reading the file and issuing a PostQueuedCompletionStatus
to do a send using WSASend
through the IO Worker threads, the function sends file in chunks and when each chunk completes the IO Worker threads will inform the main thread with PostMessage
to issue another send of the next chunk.
Now where i am supposed to increase this RefCount
? in the main thread just before issuing a call to PostQueuedCompletionStatus
? but what if a return from GetQueuedCompletionStatus
returned and freed the Per Socket structure and the main thread still using it? (Example the main thread is executing the send function but not yet increased the RefCount
) i tried to increase RefCount
in the WSASend
function in the IO Worker threads but it is the same issue
For instance: what if a thread woke up from GetQueuedCompletionStatus
as a socket closure(caused by the outstanding WSARecv
) and decrement the RefCount
and it became 0 so it will free the Per Socket structure while a WSASend
is executing in another IO Worker thread but not yet increased the RefCount
? then obviously the thread that is about to issue a WSASend
call will crash with access violation whenever it tries to enter the critical section.
Any idea how to synchronize access to this structure between IO Worker threads and the main thread?