gpt4 book ai didi

创建 3 个线程并使用 WSAWaitForMultipleEvents() 和 WSAEnumNetworkEvents() 时 CPU 使用率 100%

转载 作者:可可西里 更新时间:2023-11-01 10:06:59 27 4
gpt4 key购买 nike

我创建了 3 个线程,每个线程都有一个套接字。在每个线程中,套接字被设置为“事件驱动”,并且每当数据可供读取时,就会生成一个事件。

该代码工作正常,但它占用 CPU 使用率高达 100%,这肯定是不可取的。我想我犯了一些错误。下面是我的代码。请帮助我找出导致 100% CPU 使用率的错误。

代码:

DWORD WINAPI ThreadProc(LPVOID param)
{
int threadNumber= (int)param;
int PORT = 8888+threadNumber; //so that each thread bind()s its socket to a different Port number.
WSADATA wsa;

//Initialise winsock//
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{

//"WinSock Initialization FAILED",

}

//Create a socket//

SOCKET newSocketIdentifier;
SOCKADDR_IN newSocket;

if((newSocketIdentifier = socket(AF_INET , SOCK_DGRAM , 0 )) == INVALID_SOCKET)
{

//Socket Creation Failed

}
//Socket Created//

//Prepare the sockaddr_in structure//
newSocket.sin_family = AF_INET;
newSocket.sin_addr.s_addr = INADDR_ANY;
newSocket.sin_port = htons(PORT);

//Bind//
if( bind(newSocketIdentifier ,(struct sockaddr *)&newSocket, sizeof(SOCKADDR_IN)) == SOCKET_ERROR)
{
//Bind Failed
}

//Bind Done//
char data[256];
int bytes, waitRet;

WSAEVENT hEvent = WSACreateEvent();
WSANETWORKEVENTS events;
WSAEventSelect(newSocketIdentifier, hEvent, FD_READ | FD_WRITE);

while(1)
{
waitRet = WSAWaitForMultipleEvents(2, &hEvent, FALSE, WSA_INFINITE, FALSE);
if(WSAEnumNetworkEvents(newSocketIdentifier,hEvent,&events) == SOCKET_ERROR)
//Error
else
{
if(events.lNetworkEvents & FD_READ)
{
//call recvfrom()
}
}
}

WSACloseEvent(hEvent);
return 0;
}

int WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd )
{

HANDLE threadHandle[3];
DWORD threadId = 0;
int max_number=3;
//Start the threads
for (int i = 0; i < max_number; i++)
{
threadHandle[i]= CreateThread( NULL,
0,
ThreadProc,
(LPVOID) i,
0,
NULL
);
}

return 0;
}

最佳答案

这是一个错误:

waitRet = WSAWaitForMultipleEvents(2, &hEvent, FALSE, WSA_INFINITE, FALSE);

因为它说明在提供的事件数组中有两个事件,实际情况并非如此,因为只有 1 个。来自 WSAWaitForMultipleEvents()描述第一个参数的引用页:

The number of event object handles in the array pointed to by lphEvents. The maximum number of event object handles is WSA_MAXIMUM_WAIT_EVENTS. One or more events must be specified.

我怀疑这会导致未定义的行为,因为 WSAWaitForMultipleEvents() 正在访问数组的边界,可能导致函数无法阻塞,从而导致繁忙的循环。

此外,请参阅 Rohan 的回答关于 WSAResetEvent() 的使用。

关于创建 3 个线程并使用 WSAWaitForMultipleEvents() 和 WSAEnumNetworkEvents() 时 CPU 使用率 100%,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16417837/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com