【发布时间】: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;
}
对不起我的英语。
【问题讨论】:
-
请提供更多代码。
host、port和addrresult在哪里以及如何声明和使用?
标签: multithreading sockets winsock