Winsock spawns multiple persistent threads uncontrollably
I am developing a networking infrastructure that uses WSAEventSelect
for asynchronous operations. I create one stream for every 64th socket due to a maximum of 64 events per stream limit and everything works as expected except for one:
Threads continue to be tirelessly generated by Winsock during connection and disconnection, threads that won't go away.
With the existing design of the framework, two threads should be started when only a few sockets are active. And as expected there are two threads running. However, when I connect with multiple sockets (1-5 sockets), 3 more streams appear and persist until I close the application. Also, when I lose connection on any of the sockets, 2 more threads are generated (also saved until closed). There are 7 threads in total, 5 of which I don't know what they exist for.
If Winsock needs them to connect or whatever and then disappear, that would be fine. But it worries me that they persist until I close my application.
Is there anyone who could shed some light on this? Perhaps a solution is to avoid these threads, or force them to close when no connections are active?
(app is written in C ++ with Win32 and Winsock 2.2)
Information from Process Explorer:
Threads Expected:
MyApp.exe! WinMainCRTStartup
MyApp.exe! Netfw :: NetworkThread :: ThreadProc
Unexpected threads:
ntdll.dll! RtlpUnWaitCriticalSection + 0x2dc
mswsock.dll + 0x7426
ntdll.dll! RtlGetCurrentPeb + 0x155
ntdll.dll! RtlGetCurrentPeb + 0x155
ntdll.dll! RtlGetCurrentPeb + 0x155
All unexpected threads have call stacks with calls to functions such as ntkrnlpa.exe!IoSetCompletionRoutineEx+0x46e
, which probably means that this is part of the notification mechanism.
a source to share
Download the sysinternals process handler tool . Install the appropriate debugging tools for windows . In Process Explorer, set for Options → Symbols the path to:
SRV*C:\Websymbols*http://msdl.microsoft.com/download/symbols
Where C: \ Websymbols is just a place to store the symbol cache (I would create a new empty directory for it.)
You can now test your program using the process explorer. Double click the process, go to the topics tab and it will show you where the threads started, how busy they are and what their current column is.
This usually gives you a very good idea of what streams are. If these are internal Winsock threads, I wouldn't bother with them, even if there are hundreds of them.
a source to share