我对线程优先级和亲和力感到很开心。我在做什么,我看到至少一个问题 - 当我只使用一个CPU时,线程没有得到处理器时间。例如,我在这里有一些观察结果。
第一列是以ms为单位的时间,第二列是线程优先级等于0时的计数器,第三列和第四列是优先级为-1时的计数器,第五列和第六列是优先级为-2时的计数器。 这是我的代码:
DWORD WINAPI thread( void* counter )
{
DWORD* local = ( DWORD* )counter;
while (1)
{
for (int i = 0; i < 5000; i++)
{
suma += sin( i );
}
++(*local);
suma = 0;
}
}
int main( )
{
DWORD_PTR affinity = 1;
SetProcessAffinityMask( GetCurrentProcess( ), affinity );
LPDWORD counters = ( LPDWORD )calloc( THREADS, sizeof( DWORD ) );
int normalPriorityIndex = 0;
int lowPriorityIndex[2] = { 1, 2 };
int idlePriorityIndex[2] = { 3, 4 };
HANDLE hw[THREADS] = {
CreateThread( 0, 0, thread, counters + normalPriorityIndex, 0, 0 ),
CreateThread( 0, 0, thread, counters + lowPriorityIndex[0], 0, 0 ),
CreateThread( 0, 0, thread, counters + lowPriorityIndex[1], 0, 0 ),
CreateThread( 0, 0, thread, counters + idlePriorityIndex[0], 0, 0 ),
CreateThread( 0, 0, thread, counters + idlePriorityIndex[1], 0, 0 ),
};
SetThreadPriority( hw[normalPriorityIndex], 0 );
SetThreadPriority( hw[lowPriorityIndex[0]], -1 );
SetThreadPriority( hw[lowPriorityIndex[1]], -1 );
SetThreadPriority( hw[idlePriorityIndex[0]], -2 );
SetThreadPriority( hw[idlePriorityIndex[1]], -2 );
FILE* file;
char* fileName = ( char* )calloc( 32, sizeof( char ) );
fileName = "dane.txt";
fopen_s( &file, fileName, "w" );
DWORD startTime = GetTickCount( );
FILE* stream = stdout;
while (!_kbhit( ))
{
if (GetTickCount( ) - startTime > 600000)
{
break;
}
fprintf( file, "%5.ld | ", GetTickCount( ) - startTime );
fprintf( file, "%ld %ld %ld %ld %ld\n",
counters[normalPriorityIndex],
counters[lowPriorityIndex[0]],
counters[lowPriorityIndex[1]],
counters[idlePriorityIndex[0]],
counters[idlePriorityIndex[1]] );
Sleep( 750 );
}
for (int i = 0; i < THREADS; i++)
CloseHandle( hw[i] );
return 0;
}
为什么优先级为-2的线程有更大的计数器,然后优先级为-1的线程??