gpt4 book ai didi

c++ - Windows 7中的进程和线程优先级

转载 作者:太空宇宙 更新时间:2023-11-04 11:46:38 27 4
gpt4 key购买 nike

我有一个简单的“培训”项目,它必须显示 Windows 中的优先级机制。

这是我的 C++ 代码:

#include <stdio.h>
#include <windows.h>
DWORD WINAPI Thread1(LPVOID);
int stop;
int sleep = 10000;
struct params {
int num;
bool* runflg;
};
long long counters[7] = {0,0,0,0,0,0,0};
int priority[7] = {THREAD_PRIORITY_IDLE, THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_BELOW_NORMAL, THREAD_PRIORITY_NORMAL, THREAD_PRIORITY_ABOVE_NORMAL, THREAD_PRIORITY_HIGHEST, THREAD_PRIORITY_TIME_CRITICAL};
int main(int argc, char* argv[])
{
int thrds;
if (argc < 2) stop = 5;
else stop = atoi(argv[1]);

bool runFlag = true;
__int64 end_time;
LARGE_INTEGER end_time2;

HANDLE tm1 = CreateWaitableTimer(NULL, false, NULL);
end_time = -1 * stop * 10000000;
end_time2.LowPart = (DWORD) (end_time & 0xFFFFFFFF);
end_time2.HighPart = (LONG) (end_time >> 32);
SetWaitableTimer(tm1, &end_time2, 0,NULL, NULL, false);

//SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
printf("process priority = %d \n", GetPriorityClass(GetCurrentProcess()));
SetProcessPriorityBoost(GetCurrentProcess(), true);

for (int i = 0; i < 7; i++) {
DWORD targetThreadId;
params* param = (params*)malloc(sizeof(params));
param->num = i;
param->runflg = &runFlag;
HANDLE t1 = CreateThread(NULL, 0, Thread1, param, 0, &targetThreadId);
SetThreadPriority(t1, priority[i]); //задание приоритета

PBOOL ptr1 = (PBOOL)malloc(sizeof(BOOL));
GetThreadPriorityBoost(t1, ptr1);
SetThreadPriorityBoost(t1, true); //запрет динамического изм. приоритета

CloseHandle(t1);
}
WaitForSingleObject(tm1,INFINITE);
runFlag = false;
CloseHandle(tm1);
printf("\n");
for (int i = 0; i < 7; i++) {
printf("%d - %ld\n",i, counters[i]);
}
return 0;
}
DWORD WINAPI Thread1(LPVOID prm)
{
params arg = *((params*)prm);
printf("thread # %d priority = %d \n", arg.num, GetThreadPriority(GetCurrentThread()));

while(1) {
counters[arg.num]++;
Sleep(0);
if(*(arg.runflg) == false)
break;
}
return 0;
}

在代码中,我创建了 7 个具有不同线程优先级的线程。每个线程都有自己的计数器。该程序应该运行大约 5 秒,之后控制台必须显示线程的优先级及其值。一年前,当我在 Win XP 32 上执行此操作时,一切正常——优先级较低的线程具有较小的计数器值。但是现在我有这样奇怪的结果:

process priority = 32

thread # 0 priority = -15
thread # 1 priority = -2
thread # 2 priority = -1
thread # 3 priority = 0
thread # 4 priority = 1
thread # 5 priority = 2
thread # 6 priority = 15

0 - 5401405
1 - 5726804
2 - 6676367
3 - 8320768
4 - 3223481
5 - 3085247
6 - 3177885

为什么优先级不起作用并且计数器具有如此奇怪的值(未按升序排序)?

最佳答案

@Zilog 如何回答这个问题 - 一些奇怪 Action 的原因是在多进程 CPU 中。

如果有人想查看具有不同优先级的线程如何工作 - 他们必须使用特定的实用程序(如系统工作的监视器\分析器),或者在程序中使用特殊的 func-s,只使用一个处理器。

关于c++ - Windows 7中的进程和线程优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19618963/

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