我想限制应用程序的CPU使用率,因为我使用的是Job Objects。基本思想是使用JOB_OBJECT_LIMIT_JOB_TIME和JobObjectNotificationLimitInformation类在100毫秒的CPU时间后获取通知,然后采取适当的操作。我使用的基本代码如下:
jobinfo.jobHandle = CreateJobObject(NULL, jobname);
ZeroMemory(¬ificationLimit, sizeof(notificationLimit));
notificationLimit.LimitFlags = JOB_OBJECT_LIMIT_JOB_TIME;
/* miliseconds in 100-ns intervals. here we want notification after 100ms */
notificationLimit.PerJobUserTimeLimit.QuadPart = 100 * 10000;
SetInformationJobObject(jobinfo.jobHandle,JobObjectNotificationLimitInformation,
¬ificationLimit, sizeof(notificationLimit)))
jobinfo.portHandle = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
portInfo.CompletionKey = jobinfo.jobHandle;
portInfo.CompletionPort = jobinfo.portHandle;
SetInformationJobObject(jobinfo.jobHandle, JobObjectAssociateCompletionPortInformation,
&portInfo, sizeof(portInfo))
AssignProcessToJobObject(jobinfo.jobHandle, hProc)
在单独的线程中,我使用GetQueuedCompletionStatus()和QueryInformationJobObject()来接收通知。在线程中接收通知的代码如下:
for(;;)
{
DWORD dwNoOfBytes = 0;
ULONG_PTR ulKey = 0;
OVERLAPPED* pov = NULL;
/* Wait for a completion notification.*/
error = GetQueuedCompletionStatus(
hPort, /* Completion port handle */
&dwNoOfBytes, /* Bytes transferred */
&ulKey,
&pov, /* OVERLAPPED structure */
INFINITE /* Notification time-out interval */
);
if (!error)
printf("error");
if(pov == NULL)
{
error = GetLastError();
//continue;
}
/*
* Associate actions to job based on notification message
* and provide a way to exit the loop. Here we can do the handling
* for the case if flag to disable CPU timer is set.
*/
if (dwNoOfBytes == JOB_OBJECT_MSG_NOTIFICATION_LIMIT)
{
JOBOBJECT_LIMIT_VIOLATION_INFORMATION limitViolation;
JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION notificationLimit;
ZeroMemory(&limitViolation, sizeof(limitViolation));
error = QueryInformationJobObject(hJob,
JobObjectLimitViolationInformation,
&limitViolation, sizeof(limitViolation),
NULL);
if(!error)
{
error = GetLastError();
printf("QueryInformationJobObject failed with errorcode %d", error);
}
else if (dwNoOfBytes != JOB_OBJECT_MSG_NEW_PROCESS)
print("unexpected message received from completion port");
}
在这里,我看到几个问题: 一个。尽管API是,但GetQueuedCompletionStatus中的lpOverlapped始终为NULL 成功的,根据规格,这不应该是NULL。可能是什么原因呢? 湾即使有,也会以JOB_OBJECT_MSG_NOTIFICATION_LIMIT的消息通知消息 没有CPU使用率。 C。通知不会以指定的间隔到达,即100ms。