`
duoerbasilu
  • 浏览: 1474227 次
文章分类
社区版块
存档分类
最新评论

关于mfc下多线程socket出错

 
阅读更多
问?:

我用CSocket写通信程序,但执行到下面的函数时总出错,是什么原因?
是多线程通信,每个线程创建了一个套接字:CMySocket *m_pClientSocket = New CMySocket;
然后在OnSendSocket函数中调用:m_pClientSocket->Send(str,len);
如果消息很少,或者中间有Sleep,则没有错误,否则必然出现ASSERT(pState->m_hSocketWindow != NULL);的错误。
听说
1 是一个Bug,我用VC 5.0也打了sp5,
2 同一个套接字不能在不同的线程传输,但是我每一个线程创建了一个单独的套接字
3 没有调用AfxSockInit(),但是我在每个线程的初始化中都调用了这个函数。
现在实在没有办法解决,请大家帮忙,感谢!


下面的函数是 .../MFC/SRC/SOCKCORE.CPP 里的函数。
BOOL CSocket::PumpMessages(UINT uStopFlag)
{
// The same socket better not be blocking in more than one place.
ASSERT(m_pbBlocking == NULL);

_AFX_SOCK_THREAD_STATE* pState = _afxSockThreadState;

ASSERT(pState->m_hSocketWindow != NULL); //这句出错这句出错这句出错这句出错

BOOL bBlocking = TRUE;
m_pbBlocking = &bBlocking;

答:(from microsoft)

Most frequently, this problem is due to the sharing of CSocket objects between multiple threads.

A CSocket object should be used only in the context of a single thread because the SOCKET handle encapsulated by a CAsyncSocket object is stored in a per-thread handle map. (CSocket is derived from CAsyncSocket.) Other information is stored on a per-thread basis, including a hidden notification window that MFC uses for socket notifications.

The assertion failure line, which can be found in Sockcore.cpp in the /Msvc20/Mfc/Src directory, is:

   ASSERT(pThreadState->m_hSocketWindow != NULL);

This assertion failure occurs because the CSocket object was either created or accepted in the context of another thread. The socket notification window was created in a different thread, and the m_hSocketWindow for the current thread is NULL, thus the assertion failure.

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics