Both threading and network coding in the same project is not a beginner task. Dealing with a socket/network connection is not a big deal on an individual thread, however threading in C++ is not trivial so I give you some help in that but the networking part remains your task.
Conneciton.h:
#include <windows.h>
class CConnection
{
public:
CConnection(const std::string& hostname);
~CConnection();
bool StartServing();
void RequestStopServing();
void WaitForStopServing();
private:
void ServeConnection();
static DWORD CALLBACK StaticThreadProc(void* param);
private:
std::string m_Hostname;
HANDLE m_hThread;
};
Connection.cpp:
#include "Conneciton.h"
#include <cassert>
#include <string>
#include <vector>
#include <cstdio>
CConnection::CConnection(const std::string& hostname)
: m_Hostname(hostname)
, m_hThread(NULL)
{
}
CConnection::~CConnection()
{
assert(WaitForSingleObject(m_hThread, 0) == WAIT_OBJECT_0);
if (m_hThread)
CloseHandle(m_hThread);
}
bool CConnection::StartServing()
{
DWORD thread_id;
m_hThread = CreateThread(NULL, 0, StaticThreadProc, this, CREATE_SUSPENDED, &thread_id);
if (!m_hThread)
return false;
if (ResumeThread(m_hThread) == (DWORD)-1)
{
TerminateThread(m_hThread, 666);
CloseHandle(m_hThread);
m_hThread = NULL;
return false;
}
return true;
}
void CConnection::RequestStopServing()
{
}
void CConnection::WaitForStopServing()
{
assert(m_hThread);
if (m_hThread)
WaitForSingleObject(m_hThread, INFINITE);
}
void CConnection::ServeConnection()
{
}
DWORD CALLBACK CConnection::StaticThreadProc(void* param)
{
CConnection* instance = (CConnection*)param;
instance->ServeConnection();
return 0;
}
void StartupAndWaitConnections()
{
std::vector<CConnection*> connections;
for (int i=0; i<100; ++i)
{
std::string addr = "xyz"; CConnection* conn = new CConnection(addr);
if (!conn->StartServing())
{
printf("Error starting service for %s", addr.c_str());
delete conn;
}
connections.push_back(conn);
}
if (connections_do_not_finish_by_themselves)
{
getchar();
for (auto it=connections.begin(),eit=connections.end(); it!=eit; ++it)
{
CConnection* conn = *it;
conn->RequestStopServing();
}
}
for (auto it=connections.begin(),eit=connections.end(); it!=eit; ++it)
{
CConnection* conn = *it;
conn->WaitForStopServing();
delete conn;
}
connections.clear();
}