多线程、套接字
我有 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;
}
对不起我的英语。
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(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;
}
Sorry for my English.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它看起来像是在
addrresult
成员指针上进行竞争。您发布的方法不可重入它更新成员变量。如果您从多个线程同时调用它,您会得到惊喜。我猜测在这种特殊情况下,addrresult 可能会在一个线程中分配,然后在另一个线程中分配和覆盖。您可能最终会发生内存泄漏并访问free
-ed内存。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 theaddrresult
might be allocated in one thread, then allocated and overwritten in another. You might end up with a memory leak and with access tofree
-ed memory.