Thread abort and ThreadExit not working visualstudio2008 c++

536 views Asked by At

I'm using threads in c++ visualstudio2008, when my form closes the thread still stays active so I tried thread::abort when form is closing, but after calling about the thread is still alive. so I put am excption handler in the thread and when an abort exception arrive the thread exit, but the thread does not enter in the exception handler. how can I close my thread? oThread is a global object Thread.

private: void ThreadMethod(/*Object^ state*/)
{   
    try{
    SOCKET server;
    WSADATA wsaData;
    sockaddr_in local;
    int wsaret=WSAStartup(0x101,&wsaData);
    if(wsaret!=0)
    {
        return;
    }
    local.sin_family=AF_INET;
    local.sin_addr.S_un.S_addr=INADDR_ANY;
    local.sin_port=htons((u_short)20248);
    server=socket(AF_INET,SOCK_STREAM,0);
    if(server==INVALID_SOCKET)
    {
        return;
    }
    if(bind(server,(sockaddr*)&local,sizeof(local))!=0)
    {
        return;
    }
    if(listen(server,10)!=0)
    {
        return;
    }
    SOCKET client;
    sockaddr_in from;
    int fromlen=sizeof(from);
    int buffer;
    char buff;
    //this->Invoke(gcnew MethodInvoker(this, &Form1::UpdateButton));
    while(!stop)
    {
        client=accept(server,(struct sockaddr*)&from,&fromlen);
        //con la struct
        int numByte=recv(client,(char*) &mystruct, (int) sizeof(mystruct), 0);
        this->Invoke(gcnew MethodInvoker(this, &Form1::UpdateButton));
        MessageBox::Show(mystruct.num.ToString());
        closesocket(client);

    }
    closesocket(server);
    WSACleanup();
    }
    catch (ThreadAbortException^ e) 
    {
        ExitThread(0);
    }
    ExitThread(0);
}

private: System::Void Form1_FormClosing(System::Object^  sender, System::Windows::Forms::FormClosingEventArgs^  e) {     
         oThread->Abort(); 
         if(oThread->IsAlive)
         {
             MessageBox::Show("ok");
         }
     }
};
}
1

There are 1 answers

0
Some programmer dude On BEST ANSWER

How about something like this:

// Make socket non-blocking
int mode = 1;
ioctlsocket(server, FIONBIO, &mode);

struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 100000;  // 0.1 second

FD_SET server_set;

while (!stop)
{
    FD_ZERO(&server_set);
    FD_SET(server, &server_set);

    if (select(server + 1, &server_set, 0, 0, &timeout) == SOCKET_ERROR)
    {
        // Error handling
    }

    if (FD_ISSET(server, &server_set))
    {
        // Call accept and all the other stuff
    }
}