我有一个为WinSock编写的手册类。我的程序有多个线程。我用来同步对象(例如std::queue)和临界区。但是我的socket类中有错误:
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;
}
对不起,我的英语不好。
发布于 2011-08-17 03:33:53
这看起来像是addrresult
成员指针上的一场竞赛。您发布的方法是,因为它更新了成员变量。如果你从多个线程并发调用它,你会得到惊喜。我猜测在这种特殊情况下,addrresult
可能在一个线程中分配,然后在另一个线程中分配和覆盖。最终可能会出现内存泄漏并访问free
-ed内存。
https://stackoverflow.com/questions/7083356
复制相似问题