开发者

Multhithreading, sockets

开发者 https://www.devze.com 2023-03-29 01:04 出处:网络
I have manualy writing class for WinSock. My program have more that one threads. I use to synchronize objects(example std::queue) with critical sections.

I have manualy writing class for WinSock. My program have more that one threads. I use to synchronize objects(example std::queue) with critical sections. But I have errors in my socket class:

iResult = getaddrinfo(host.c_str(), port.c_str(), &hints, &(*this).addrresult); //permision error

In single thread mode all is OK. But if I start more that one threads, program has error. Help me.

int jSocket::ConnectSock(const std::string host, const std::string port)
{
    int iResult;
    struct addrinfo hints, *ptr;

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

    iResult = getaddrinfo(host.c_str(), port.c_str(), &hints, &(*this).addrresult);
    if (iResult != 0)
    {
        WSACleanup();
        return -1;
    }

    ptr = (*this).addrresult;
    (*this).sock = socket(p开发者_如何学JAVAtr->ai_family, ptr->ai_socktype, ptr->ai_protocol);

    if ((*this).sock == INVALID_SOCKET)
    {
        freeaddrinfo(addrresult);
        WSACleanup();
        return -1;
    }

    iResult = connect((*this).sock, ptr->ai_addr, (int)ptr->ai_addrlen);
    if (iResult == SOCKET_ERROR)
    {
        closesocket((*this).sock);
        return -1;
    }

    return 0;
}

Sorry for my English.


It looks like a race on the addrresult member pointer. The method you posted is not re-entrant since it updates member variables. If you call it concurrently from multiple threads you get surprises. I'm guessing in this particular case the addrresult might be allocated in one thread, then allocated and overwritten in another. You might end up with a memory leak and with access to free-ed memory.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号