目的:开一个线程使用套接字连接class CMySocket : public CAsyncSocket
{
public:
CMySocket();
virtual ~CMySocket(); static UINT  ConnectThread( LPVOID pParam );  // 我的线程函数private:
UINT m_nPort;
};struct THREAD_PARAM
{
CSmartSocket* _this;
};// 函数定义
UINT CMySocket::ConnectThread( LPVOID pParam )
{
THREAD_PARAM* threadparam = (THREAD_PARAM*)pParam; threadparam->_this->Connect( "127.0.0.1", threadparam->_this->m_nPort ); AfxEndThread(0); return TRUE;
}然后我这样调用:
if( this->Create() )  //  一个客户端的连接,服务器已开启
{
THREADPARAM* connnectparam = new THREADPARAM;
connnectparam->_this = this; AfxBeginThread( ConnectThread, connnectparam ); delete connnectparam;
}编译成功,但是运行时提示:
SSS.exe 中的 0x7c2b9b4c (mfc70d.dll) 处未处理的异常:0xC0000005: 读取位置 0xfeeefeee 时发生访问冲突 。中断后箭头停在文件sockcore.cpp的
BOOL CAsyncSocket::Connect(LPCTSTR lpszHostAddress, UINT nHostPort)
{
/*……*/ return Connect((SOCKADDR*)&sockAddr, sizeof(sockAddr));
}  //此处我觉得我已经把指针传过来了……先谢过大家了!!!

解决方案 »

  1.   

    在AfxBeginThread之后不要调用delete connnectparam;
      

  2.   

    UINT CMySocket::ConnectThread( LPVOID pParam )
    {
    THREAD_PARAM* threadparam = (THREAD_PARAM*)pParam; …………………… delete threadparam; AfxEndThread(0); return TRUE;
    }我在这里删掉threadparam没错吧?
      

  3.   

    原来的代码是否有可能是这样:当线程函数还没有返回甚至执行时,connnectparam就已经被delete了,所以才会出错?
      

  4.   

    我将原代码修改如下以证实:CEvent event; //  全局变量if( this->Create() )
    {
    THREADPARAM* connnectparam = new THREADPARAM;
    connnectparam->_this = this; AfxBeginThread( ConnectThread, connnectparam ); event.Lock(); // 锁定 delete connnectparam;
    }// 函数定义
    UINT CMySocket::ConnectThread( LPVOID pParam )
    {
    THREAD_PARAM* threadparam = (THREAD_PARAM*)pParam; threadparam->_this->Connect( "127.0.0.1", threadparam->_this->m_nPort ); event.SetEvent(); //解锁 AfxEndThread(0); return TRUE;
    }一切正常!