首页 新闻 会员 周边 捐助

求助大神,线程结束问题。

0
悬赏园豆:20 [待解决问题]

DWORD EM_FileReceiving::ListeningThread(LPVOID lParam)
{
//SOCKET sListen;
CEIM02Dlg *pDlg = (CEIM02Dlg *)lParam;
// Create our listening socket
pEm_fileReceiving->m_sListen = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (INVALID_SOCKET == pEm_fileReceiving->m_sListen)
{
MessageBox(0,"socket() failed:%d\n",0,0);
return 1;
}
// Select the local interface and bind to it

SOCKADDR_IN local;
local.sin_addr.s_addr = htonl(INADDR_ANY);
local.sin_family = AF_INET;
local.sin_port = htons(5150);

int ret = ::bind(pEm_fileReceiving->m_sListen, (PSOCKADDR)&local, sizeof(SOCKADDR_IN));
if (SOCKET_ERROR == ret)
{
MessageBox(0,"bind() failed:%d\n",0,0);
return 1;
}

listen(pEm_fileReceiving->m_sListen, 5);
int iAddress = sizeof(SOCKADDR_IN);
SOCKET sClient;
SOCKADDR_IN addrClient;
EnterCriticalSection(&pEm_fileReceiving->cs);
while( m_bFileReceivingThread )
{
if (!m_bFileReceivingThread)
{
break;
}
sClient = accept(pEm_fileReceiving->m_sListen, (PSOCKADDR)&addrClient, &iAddress);
if (INVALID_SOCKET == sClient)
{
MessageBox(0,"accept() failed:%d\n", 0,0);
break;
}
char *szClientIP = new char [64];
strcpy(szClientIP, inet_ntoa(addrClient.sin_addr));
pDlg->PostMessage(WM_RECVFILE, (WPARAM)sClient, (LPARAM)szClientIP);
}
LeaveCriticalSection(&pEm_fileReceiving->cs);
return 1;
}
/////////////////////////////////////////////////////////////////////////////
// EM_FileReceiving message handlers

void EM_FileReceiving::Close()
{
m_bFileReceivingThread = FALSE;
closesocket(m_sListen);
BOOL bReuseaddr=TRUE;
setsockopt(m_sListen,SOL_SOCKET ,SO_REUSEADDR,(const char*)&bReuseaddr,sizeof(BOOL));
if (m_hThread != NULL)
{
TerminateThread(m_hThread, 0);
m_hThread = NULL;
}

}

求助,为什么已经终止了线程。线程里的函数还运行。
而且m_bFileReceivingThread 已将设置为false了
但回调函数中的循环,还在运行
加sleep(1000);也不可以
waiforsingobject等待也不可以。求高手。谢谢

L_Andy的主页 L_Andy | 初学一级 | 园豆:182
提问于:2015-01-26 17:39
< >
分享
所有回答(2)
0

很仔细地看了代码,但是没看出什么… while(false)只是跳出了当前循环,并不代表线程已经结束了。

Firen | 园豆:5385 (大侠五级) | 2015-01-26 19:59

我在Close函数中也用terminateThread终止了线程,我调试了,当close函数运行完,

直接走到listenThread函数中while循环中的accept函数,前面通过判断false退出循环,根本不运行,

而且我已经释放了端口,所以accept函数就错了。我就想解决,当close函数运行完毕,while循环直接结束

不走accept函数。有什么好方法解决吗??谢谢大神。

支持(0) 反对(0) L_Andy | 园豆:182 (初学一级) | 2015-01-27 10:05
0

你需要的只是对accept函数做个异常处理

garry | 园豆:495 (菜鸟二级) | 2015-01-28 16:01
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册