CSocket在多线程环境下使用Static库出错的解决办法

 
CSocket在多线程环境下使用Static库出错的解决办法
 
 
这几天都在做密码课程实践,其中需要做一个双机密码演示,需要用DH密钥交换协议交换密钥,然后再用一种对称密钥对双机通讯信息进行加解密。我用MFC来做的,主程序采用CAsyncSocket异步通讯的方式。选择CAsyncSocket是因为它是异步的,可以采用实践触发模式。在进行文件传输的时候,我采用了多线程加CSocket的方法,即在一个新创建的线程内采用CSocket同步模式传输文件。整个工程采用Static库。在Debug下,文件传输一切正常,可是到了Release底下一旦在新创建新线程CSocket调用Create之后,就抛出异常了,程序异常退出。上网查了半天,终于在CSDN的一个2002年的帖子上发现原因。原帖如下:

FIX: Unhandled Exception Using MFC Sockets in Visual C++ 6.0  
The information in this article applies to:
The Microsoft Foundation Classes (MFC), when used with:
Microsoft Visual C++, 32-bit Enterprise Edition 6.0
Microsoft Visual C++, 32-bit Professional Edition 6.0
Microsoft Visual C++, 32-bit Learning Edition 6.0  
Symptoms
When using MFC sockets in secondary threads in a statically linked MFC Visual C++ 6.0 application, an unhandled exception occurs.
Cause
The reason for the unhandled exception is that an object of type CMapPtrToPtr pointer, pointed to by m_pmapSocketHandle, is never created.
Resolution
The handle maps used by the sockets need to be created for each thread. The following code shows a function to do this:

void SocketThreadInit() 

#ifndef    _AFXDLL 
#define    _AFX_SOCK_THREAD_STATE    AFX_MODULE_THREAD_STATE 
#define    _afxSockThreadState    AfxGetModuleThreadState() 
      _AFX_SOCK_THREAD_STATE*    pState = _afxSockThreadState; 
      if(pState->m_pmapSocketHandle == NULL) 
            pState->m_pmapSocketHandle = new CMapPtrToPtr; 
      if(pState->m_pmapDeadSockets == NULL) 
            pState->m_pmapDeadSockets = new CMapPtrToPtr; 
      if(pState->m_plistSocketNotifications == NULL) 
            pState->m_plistSocketNotifications = new CPtrList; 
#endif 
}
This function should be called once in each secondary thread before the first socket is created in the new thread.
在每个线程开始出调用SocketThreadInit函数,就没有问题了。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值