Multithreaded server application - increase in application memory usage
The service application works well when no thread is created upon receiving new client request. Appreciate if someone can give me a hand on this. Thanks.
Below are snippets of the codes:
// service main function
void CMyService::ServiceMain(DWORD /*dwArgc*/, LPTSTR* /*lpszArgv*/)
{
:
:
CAsyncSocket socListen;
if (!socListen.Create(8080))
{
QuitService(strMsg);
return;
}
if (!socListen.Listen(200))
{
QuitService(strMsg);
return;
}
:
:
CSocket soc;
CMyThread* pThread;
while(!m_bStop)
{
if (socListen.Accept(soc))
{
pThread = (CMyThread*)AfxBeginThread(RUNTIME_CLASS(CMyThread), THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED);
if (!pThread)
{
soc.Close();
strMsg.Format(_T("Failed to create serving thread. Error: %s."), GetLastErrorText(GetLastError()));
AfxGetService()->m_EventLogSource.Report(EVENTLOG_ERROR_TYPE, CS_MSG_SERVICE_ERROR, strMsg);
return;
}
// Pass the socket to the thread by passing the socket handle.
pThread->m_hSocket = soc.Detach();
// start the thread.
pThread->ResumeThread();
}
Sleep(1000);
}
:
:
}
// CMyThread class: MyThread.h
class CMyThread : public CWinThread
{
DECLARE_DYNCREATE(CMyThread)
protected:
CMyThread(); // protected constructor used by dynamic creation
virtual ~CMyThread();
public:
// Used to pass the socket handle from the main thread to this thread.
SOCKET m_hSocket;
// CSocket derived class that handles the connection.
CSock m_socket;
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CMyThread)
public:
virtual BOOL InitInstance();
virtual int ExitInstance();
virtual int Run();
//}}AFX_VIRTUAL
};
// CMyThread class: MyThread.cpp
#include "MyThread.h"
IMPLEMENT_DYNCREATE(CMyThread, CWinThread)
CMyThread::CMyThread()
{
m_bAutoDelete = TRUE;
}
CMyThread::~CMyThread()
{
}
BOOL CMyThread::InitInstance()
{
:
:
// Attach the socket handle to a CSocket object.
m_socket.Attach(m_hSocket);
m_socket.m_pThread = this;
:
:
return TRUE;
}
int CMyThread::ExitInstance()
{
m_socket.ShutDown();
m_socket.Close();
:
:
return CWinThread::ExitInstance();
}
int CMyThread::Run()
{
// TODO: Add your specialized code here and/or call the base class
PostQuitMessage(0);
return CWinThread::Run();
}

