我使用VS2008和Win7在C ++中工作。
在检查程序时,我跟踪创建的线程,似乎gethostbyname()为自己创建了一个线程。你能解释一下原因吗?
在msdn上说: “gethostbyname函数返回的hostent结构的内存由Winsock DLL从线程本地存储内部分配。”
这个记忆是否让视觉工作室认为它是一个线程?
编辑:似乎来自this link,以及我的观察,这也发生在连接功能上。我想这是正常行为。
以下代码来自msdn [gethostbyname page],它表现出相同的行为。
int main(int argc, char **argv)
{
//-----------------------------------------
// Declare and initialize variables
WSADATA wsaData;
int iResult;
DWORD dwError;
int i = 0;
struct hostent *remoteHost;
char *host_name;
struct in_addr addr;
char **pAlias;
// Validate the parameters
if (argc != 2) {
printf("usage: %s hostname\n", argv[0]);
printf(" to return the IP addresses for the host\n");
printf(" %s www.contoso.com\n", argv[0]);
printf(" or\n");
printf(" %s IPv4string\n", argv[0]);
printf(" to return an IPv4 binary address for an IPv4string\n");
printf(" %s 127.0.0.1\n", argv[0]);
return 1;
}
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed: %d\n", iResult);
return 1;
}
host_name = argv[1];
printf("Calling gethostbyname with %s\n", host_name);
remoteHost = gethostbyname(host_name);
if (remoteHost == NULL) {
dwError = WSAGetLastError();
if (dwError != 0) {
if (dwError == WSAHOST_NOT_FOUND) {
printf("Host not found\n");
return 1;
} else if (dwError == WSANO_DATA) {
printf("No data record found\n");
return 1;
} else {
printf("Function failed with error: %ld\n", dwError);
return 1;
}
}
} else {
printf("Function returned:\n");
printf("\tOfficial name: %s\n", remoteHost->h_name);
for (pAlias = remoteHost->h_aliases; *pAlias != 0; pAlias++) {
printf("\tAlternate name #%d: %s\n", ++i, *pAlias);
}
printf("\tAddress type: ");
switch (remoteHost->h_addrtype) {
case AF_INET:
printf("AF_INET\n");
break;
case AF_NETBIOS:
printf("AF_NETBIOS\n");
break;
default:
printf(" %d\n", remoteHost->h_addrtype);
break;
}
printf("\tAddress length: %d\n", remoteHost->h_length);
i = 0;
if (remoteHost->h_addrtype == AF_INET)
{
while (remoteHost->h_addr_list[i] != 0) {
addr.s_addr = *(u_long *) remoteHost->h_addr_list[i++];
printf("\tIP Address #%d: %s\n", i, inet_ntoa(addr));
}
}
else if (remoteHost->h_addrtype == AF_NETBIOS)
{
printf("NETBIOS address was returned\n");
}
}
return 0;
}
答案 0 :(得分:3)
AFAIK,gethostbyname blocks。
WinSock通常会创建一些帮助程序线程。
答案 1 :(得分:1)
不,线程本地存储与新线程的启动无关。
由于与GetHostByName API的子操作的线程相关性问题,可能需要该线程,例如需要使用异步回调而不影响调用线程的重入。
或者它可能是WinSock的延迟初始化功能,其中需要一个WinSock操作子集所需的守护程序线程,这是第一个需要该守护程序的API。