Click here to Skip to main content
15,893,161 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
In one of my program i have to create 100 thread to connect to machine using socket connection.
To do all this i have to main 100 sockets and 100 buffer that is to be pass to the recv() call to collect data from the machine.
As i am a beginner i got the following suggestion:-


you have to have some class that represents the connection - it should have hostname/IP string, socket handle, a thread handle and read/write buffer data members. Pass in the hostname/IP string as a ctor parameter and then, in the ctor, store the hostname/IP and create a thread, (passing 'this' as thread create parameter so that the thread function can call a 'run' method of the connection), to do the connect, read, write using the private buffer/s. Each connection class instance would then operate on its own - no need for any globals


So i did the following:-


C++
//ITS an pseudo class
class connection
{
struct host
{
char *ip[100];
int port[100];
}h;

SOCKET ConnectSocket1 = INVALID_SOCKET;
SOCKET ConnectSocket2 = INVALID_SOCKET;
SOCKET ConnectSocket3 = INVALID_SOCKET;
SOCKET ConnectSocket4 = INVALID_SOCKET;
SOCKET ConnectSocket5 = INVALID_SOCKET;
SOCKET ConnectSocket6 = INVALID_SOCKET;
SOCKET ConnectSocket7 = INVALID_SOCKET;
     ......
SOCKET ConnectSocket100 = INVALID_SOCKET;

HANDLE Sock_ThreadHandle[100];

DWORD FIComThreadId1;
DWORD FIComThreadId2;
DWORD FIComThreadId3;
DWORD FIComThreadId4;
DWORD FIComThreadId5;
DWORD FIComThreadId6;
DWORD FIComThreadId7;
  .......
DWORD FIComThreadId100;


char buf1[200];
char buf2[200];
char buf3[200];
char buf4[200];
char buf5[200];
char buf6[200];
char buf7[200];
char buf8[200];
char buf9[200];
 ......
char buf100[200];




}con;




Now in the implementation part
C++
int main()
{
//i will get the ip and port from the database
//function to get the ip and port from the database

createeThread(ip,port);

};
createeThread(ip,port)
{
//here thread will be created how to pass the  private buffer and ip and port to the thread and in thread connect,send,recv call will be called

}


Please tell me,i am all new to it
Posted
Comments
Quirkafleeg 20-Sep-12 4:19am    
I think the first thing you need to do is learn what arrays can do...
I grant bravery for publishing it, but creating 300 variables kind of shows that you may not be ready to handle either socket or multi-threaded programming just yet.
pasztorpisti 21-Sep-12 7:10am    
"+5"
Tarun Batra 1-Oct-12 10:29am    
can u please answer http://www.codeproject.com/Questions/468868/Can-u-tell-whats-the-problem-in-the-below-function

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:
C++
#include <windows.h>

class CConnection
{
public:
	// pass as many parameters as you want
	CConnection(const std::string& hostname);
	~CConnection();
	// Starts a thread and calls youer ServeConnection() method, returns false on error.
	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:
C++
#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()
{
	// checking if the thread has terminated
	assert(WaitForSingleObject(m_hThread, 0) == WAIT_OBJECT_0);
	if (m_hThread)
		CloseHandle(m_hThread);
}


bool CConnection::StartServing()
{
	DWORD thread_id;
	// We use creatsuspended to make sure that m_hThread is initialized before the thread actually starts execution.
	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()
{
	// TODO: This is called from the main thread, somehow you signal to your network thread that
	// it should close the connection and return from the ServeConnection() method.
}

void CConnection::WaitForStopServing()
{
	assert(m_hThread);
	if (m_hThread)
		WaitForSingleObject(m_hThread, INFINITE);
}

void CConnection::ServeConnection()
{
	// Your network code comes here. You should put in network handling and checking if
	// RequestStopServing() has been called or not.
}

DWORD CALLBACK CConnection::StaticThreadProc(void* param)
{
	CConnection* instance = (CConnection*)param;
	instance->ServeConnection();
	return 0;
}

// put this to whatever cpp you like
void StartupAndWaitConnections()
{
	std::vector<CConnection*> connections;
	for (int i=0; i<100; ++i)
	{
		std::string addr = "xyz"; // Get some address from somewhere
		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)
	{
		// Here do whatever you want on your main thread, I do wait for an ENTER keypress...
		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();
}
 
Share this answer
 
v3
Comments
Tarun Batra 21-Sep-12 7:33am    
Really thanks for the code but i too have queries
Tarun Batra 1-Oct-12 10:28am    
can u please answer http://www.codeproject.com/Questions/468868/Can-u-tell-whats-the-problem-in-the-below-function
You don't need one class with 100 data members of each time, you only need one data member of each type, and then define 100 instances of that class. Also, don't define 100 variables to hold these instances, instead use some kind of container. A simple C-style array would do, but it would be more flexible to use std::vector.

Next you need to define a constructor, destructor (optional, depending on your data members) and methods (e. g. run(), connect(), disconnect()) for this class. That was already suggested to you.

That said, your program shows that you may not be familiar with all this terminology and technique at all. Did you know that ctor is an abbreviation for constructor? Or are you even familiar with the concept of arrays?

If that is your problem, then you are simply not ready to create programs involving threads at all. Not trying to be offensive, but threads are really an advanced concept of programming, and you really need to learn to walk before you start to run.
 
Share this answer
 
Comments
Tarun Batra 1-Oct-12 10:28am    
can u please answer http://www.codeproject.com/Questions/468868/Can-u-tell-whats-the-problem-in-the-below-function
What do you want to do ?
please specify your task.
 
Share this answer
 
Comments
Tarun Batra 20-Sep-12 2:58am    
can u just tell the following:- as i have stated i have to create 100 threads so to make 100 connection i need have to 100 buffer,so to do the task i got the following suggestion:-you'll have to create an object for each thread and pass it to the thread upon thread creation. When you execute the common thread function, pass the thread's object's buffer to recv(). you have to have some class that represents the connection - it should have hostname/IP string, socket handle, a thread handle and read/write buffer data members. Pass in the hostname/IP string as a ctor parameter and then, in the ctor, store the hostname/IP and create a thread, (passing 'this' as thread create parameter so that the thread function can call a 'run' method of the connection), to do the connect, read, write using the private buffer/s. Each connection class instance would then operate on its own - no need for any globals.How to implement this.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900