如何检查是否应该关闭线程句柄 [英] How to check if a thread handle should be closed

查看:97
本文介绍了如何检查是否应该关闭线程句柄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个服务器应用程序,该应用程序具有一个套接字,用于侦听来自客户端的连接请求.永远只有一个客户.因此,我有一个while(1)循环,该循环检查是否有到客户端的套接字连接并包含accept()方法.当accept()返回时,将创建一个新线程来处理客户端连接.如果客户端断开连接,则while(1)循环将使用getsockname()进行检测,然后允许accept()建立另一个连接,并允许一个新线程来处理该连接.

我想确保,如果套接字连接已关闭,我也将关闭其线程句柄,以防止内存泄漏.但是我需要在while(1)循环中执行此操作.启动后第一次进入此循环,该句柄将无效,因此,如果我执行CloseHandle(hThread),则会收到错误消息.如果我在调用CloseHandle(hThread)之前检查if(hThread!= NULL),它仍然会抱怨"if"语句,因为句柄无效.如何在创建新代码之前更改代码以确保为线程句柄分配内存?

请有人告诉我我要去哪里错了.

I am writing a server application which has a socket which listens for a connection request from a client. There will only ever be one client. So I have a while(1) loop which checks if there is a socket connection to a client and contains the accept() method. When accept() returns, a new thread is created to handle the client connection. If the client disconnects, the while(1) loop will detect this using getsockname() and then allow accept() to make another connection and a new thread to handle the connection.

I want to ensure that if a socket connection is closed that I close its thread handle as well in order to prevent a memory leak. But I need to do this in the while(1) loop. The first time this loop is entered after startup, the handle will not be valid, so if I do CloseHandle(hThread), I get an error. If I check if(hThread != NULL) before I call CloseHandle(hThread) it still complains about the ''if'' statement because the handle is invalid. How can I chnage my code to ensure I deallocate the memory for the thread handle before a new one is created?

Please could somebody tell me where I am going wrong.

DWORD WINAPI StartListeningThread(void *param)//(LPVOID iValue)
{
	CCCDSocket listenSock;
	SOCKET ls;
        HANDLE hRecvThread; 

	//create socket up to and including listen()
	bool listenSockReturn = listenSock.CreateListeningSocket(ls);
	
	//continually check if the listening socket has accepted a connection
        //request from a client, and a socket connection has been made. If the
        //connected socket loses its connection, accept a new connection request
	while(1) 
	{
                if(hRecvThread != NULL)//this causes an error at run-time as the 
                                       //hRecvThread is not valid!!! But that is
                                       //what I want to test for.
                {
                    CloseHandle(hRecvThread)
                }

         	//check if the connected socket has been closed, as then a new 
                //connection request needs to be accepted
		struct sockaddr_storage addr;
		int addrLen = sizeof(addr);

                //this will fail if the socket has been closed
		if(getsockname(sr,(LPSOCKADDR)&addr, &addrLen) ==SOCKET_ERROR)
		{
			//accept the new connection request from the client 
			sr = accept(ls, 0, 0);

			DWORD dwClientHandlerThreadID;
			hRecvThread = CreateThread(NULL, NULL, 
                                                    CreateClientHandlerThread, 
                                                    NULL, NULL, 
                                                    &dwClientHandlerThreadID);
		}
	}
	return 0;		
}

推荐答案

第一部分很简单,但是并不能解决您的问题.

The first part is easy but it won''t solve your problems.

HANDLE hRecvThread = NULL;




第二部分比较困难.这不是终止线程的方法.

1.您必须允许线程main退出自身.如果线程被阻塞(正在等待),这是一个棘手的过程.
2.然后,您可以等待发出信号的线程句柄,表明线程已退出.
3.然后,您可以在线程句柄上调用CloseHandle().

这给了你这个主意.




The second part is more difficult. This is not the way to terminate a thread.

1. You must allow the thread main to exit itself. This is a tricky process if the thread is blocked (waiting).
2. You can then wait on the thread handle to be signaled indicating thread has exited.
3. You may then call CloseHandle() on the thread handle.

This gives you the idea.

dwResult = ::WaitForSingleObject(m_hThread, killTimeOut);

switch(dwResult)
{
    // If get to here then thread exits normally.
    case WAIT_OBJECT_0:
        ::CloseHandle(m_hThread);
         m_hThread = NULL;
    break;

    case WAIT_TIMEOUT:
    default:
        bRetVal = false;
    break;
}



这里涉及的开销和时间延迟通常意味着服务器中使用了某种类型的线程池.这样可以避免在运行中破坏和创建线程.

http://msdn.microsoft.com/zh-CN /library/windows/desktop/ms686724(v=vs.85).aspx [



The overheads and time delays involved here usually means some kind of thread pooling is used in servers. This avoids having to destroy and create threads on the fly.

http://msdn.microsoft.com/en-us/library/windows/desktop/ms686724(v=vs.85).aspx[^]


这篇关于如何检查是否应该关闭线程句柄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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