I have a tcp acceptor class,
pseudo codes
class TcpAcceptor
{
SOCKET listener;
volatile unsigned int m_pendingAccepts;
void AcceptAsync(OverlappedAccept *ovl)
{
InterlockedIncrement(&m_pendingAccepts);
BOOL cbl = AcceptEx(listener, newSocket()....);
if fails call decrement
}
void Stop()
{
closesocket(m_listener);
m_listener = INVALID_SOCKET
InterlockedWait(&m_pendingAccepts, 0);
}
}
TcpAcceptor acp;
for (i = 0; i < 100; i++)
acp.AcceptAsync(new overlapped());
acp.Stop();
lets assume, program is executed closesocket function in Stop() (m_listener isnt set to invalid_socket yet), then another thread calls AcceptEx with that old handle (maybe anywhere in program would create new socket and having same handle with listener's handle, so erroneous implement)
I don't want to lock AcceptEx and Stop functions because I don't have any sync problems until I call Stop()
so how can I close listener socket and terminate accepts properly?