请告诉我,如何在C ++,VC ++中执行以下操作,我可以创建一个线程 [英] Please tell me,How to do the following in C++,VC++,I can create one thread

查看:58
本文介绍了请告诉我,如何在C ++,VC ++中执行以下操作,我可以创建一个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序之一中,我必须创建100个线程以使用套接字连接来连接到计算机.
为此,我必须主要使用100个套接字和100个缓冲区,这些缓冲区将传递给recv()调用以从计算机中收集数据.
作为初学者,我得到以下建议:-


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

推荐答案

同一项目中的线程和网络编码都不是初学者.在单独的线程上处理套接字/网络连接并不是什么大问题,但是C ++中的线程并不是微不足道的,因此在这方面我会给您一些帮助,但是联网部分仍然是您的任务.

Conneciton.h:
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:



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();
}


您不需要每次都具有100个数据成员的一个类,只需要每种类型的一个数据成员,然后定义100个实例此类.另外,不要定义100个变量来保存这些实例,而要使用某种容器.一个简单的C样式数组就可以,但是使用std::vector会更灵活.

接下来,您需要定义一个构造函数析构函数(可选,具体取决于您的数据成员)和方法(例如run()disconnect()).已经建议您了.

也就是说,您的程序表明您可能根本不熟悉所有这些术语和技术.您知道 ctor constructor 的缩写吗?还是您甚至熟悉数组的概念?

如果那是您的问题,那么您根本就不准备创建涉及线程的程序.并不是冒犯,而是线程实际上是编程的高级概念,在开始运行之前,您确实需要学习走路.
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.


您想做什么?
请指定您的任务.
What do you want to do ?
please specify your task.


这篇关于请告诉我,如何在C ++,VC ++中执行以下操作,我可以创建一个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆