Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++ C Visual-Studio VC++
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:-
 

//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
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 19-Sep-12 20:43pm
Comments
Quirkafleeg at 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 at 21-Sep-12 7:10am
   
"+5"
Tarun Batra at 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
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 6

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:
	// 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:
#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();
}
  Permalink  
v3
Comments
Tarun Batra at 21-Sep-12 7:33am
   
Really thanks for the code but i too have queries
Tarun Batra at 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
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

What do you want to do ?
please specify your task.
  Permalink  
Comments
Tarun Batra at 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.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 5

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.
  Permalink  
Comments
Tarun Batra at 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

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

  Print Answers RSS
0 OriginalGriff 6,034
1 Sergey Alexandrovich Kryukov 4,838
2 Peter Leow 3,129
3 Maciej Los 3,079
4 DamithSL 2,465


Advertise | Privacy | Mobile
Web02 | 2.8.140721.1 | Last Updated 21 Sep 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100