今天無聊就想隨便測試一下所謂線程優先級的高低到底對時間片分配有多大影響,測試代碼如下:
DWord CALLBACK thread_fun2 (LPVOID);
long i=0;
int cnt_1=0;
int cnt_2=0;
#define CNT 60000
DWord CALLBACK thread_fun1 (LPVOID lpParam)
{
DWord thread_id;
PHANDLE phThread2=(PHANDLE)lpParam;
SECURITY_ATTRIBUTES sa;
int i_bak=0;
sa.nLength=sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle=TRUE;
sa.lpSecurityDescriptor=NULL;
*phThread2=CreateThread (&sa,0,thread_fun2,(LPVOID)NULL,CREATE_SUSPENDED,&thread_id);
SetThreadPriority (*phThread2,THREAD_PRIORITY_IDLE);
ResumeThread (*phThread2);
//Sleep (0); //Sleep (1);
//for (int j=0;j<10000;j++)
// Sleep (0);
do
{
i_bak=InterlockedExchangeAdd (&i,1);
printf ("thread1:%d\n",i_bak);
cnt_1++;
}while (i_bak<CNT);
printf ("thread1 ended!\n");
return 0;
}
DWord CALLBACK thread_fun2 (LPVOID lpParam)
{
int i_bak=0;
//Sleep (0);
do
{
i_bak=InterlockedExchangeAdd (&i,1);
printf ("thread2:%d\n",i_bak);
cnt_2++;
}while (i_bak<CNT);
printf ("thread2 ended!\n");
return 0;
}
int main ()
{
SECURITY_ATTRIBUTES sa;
sa.nLength=sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle=TRUE;
sa.lpSecurityDescriptor=NULL;
DWord thread_id;
HANDLE hThread2;
HANDLE hThread1=CreateThread (&sa,0,thread_fun1,(LPVOID)(&hThread2),CREATE_SUSPENDED,&thread_id);
SetThreadPriority (hThread1,THREAD_PRIORITY_BELOW_NORMAL);
ResumeThread (hThread1);
WaitForSingleObject (hThread1,INFINITE);
WaitForSingleObject (hThread2,INFINITE);
printf ("cnt_1:%d\tcnt_2:%d\n",cnt_1,cnt_2); //線程1,2的執行次數
return 0;
}
首先,用上面代碼運行肯定會出現CPU占用100%,但具體是哪個進程占用CPU呢?我一開始以為會是進程本身,常理就是如此,但實際上是CSRSS進程占用92%左右的CPU.
CSRSS是操作系統負責處理圖形界面的進程.也就是說printf函數執行後程序等待CSRSS處理實際的輸出工作,進程本身已經被阻塞了,