【问题标题】:Multhithreading, sockets多线程,套接字
【发布时间】:2011-08-17 03:33:53
【问题描述】:

我有手动编写 WinSock 的课程。我的程序有多个线程。我用来将对象(例如 std::queue)与临界区同步。 但是我的套接字类中有错误:

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

在单线程模式下一切正常。但是如果我启动多个线程,程序就会出错。帮帮我。

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(ptr->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;
}

对不起我的英语。

【问题讨论】:

  • 请提供更多代码。 hostportaddrresult 在哪里以及如何声明和使用?

标签: multithreading sockets winsock


【解决方案1】:

看起来像addrresult 成员指针上的竞赛。您发布的方法是 not re-entrant,因为它会更新成员变量。如果你从多个线程同时调用它,你会得到惊喜。我猜在这种特殊情况下,addrresult 可能会在一个线程中分配,然后在另一个线程中分配和覆盖。您最终可能会出现内存泄漏并可以访问free-ed 内存。

【讨论】:

  • 这个方法是类的成员。为每个线程程序创建了新的类对象。为什么 addresult 内存重定位?
  • function_check - 这个函数使用套接字,她为套接字创建了新对象。 function_run - 这个函数是多线程的,她使用function_check。我启动程序,调试器显示错误。
  • 再一次,没有足够的代码告诉你出了什么问题。尝试将您的程序缩减为仍然存在问题的最小样本,然后发布。
猜你喜欢
  • 2011-02-11
  • 2020-03-28
  • 2016-07-23
  • 1970-01-01
  • 1970-01-01
  • 2012-12-08
  • 2012-05-17
  • 2013-05-03
  • 2016-03-16
相关资源
最近更新 更多