線程管理
線程創(chuàng)建
#include <stdio.h>
#include <windows.h>
DWORD WINAPI ThreadProc(LPVOID lpParam)
{
int i=0;
while(i<20)
{
printf("I am form a thread,count= %d \n",i++);
}
return 0;
}
int main(int argc,char* argv[])
{
HANDLE hThread;
DWORD dwThreadId;
hThread = ::CreateThread(NULL,NULL,ThreadProc,NULL,0,&dwThreadId);
printf("Id = %d \n",dwThreadId);
::WaitForSingleObject(hThread,INFINITE); //等待線程結(jié)束
::CloseHandle(hThread); //關(guān)閉句柄
return 0;
}
優(yōu)先級(jí)管理
線程之間存在優(yōu)先級(jí)問(wèn)題,如下解決
#include <windows.h>
#include <stdio.h>
DWORD WINAPI ThreadIdle(LPVOID lpParam)
{
int i=0;
while(i++<10)
printf("Idle Thread runing \n");
return 0;
}
DWORD WINAPI ThreadNormal(LPVOID lpParam)
{
int i=0;
while(i++ < 10)
printf("Normal Thread runing \n");
return 0;
}
int main(int argc,char* argv[])
{
DWORD dwThreadId;
HANDLE h[2];
h[0]=::CreateThread(NULL,0,ThreadIdle,NULL,CREATE_SUSPENDED,&dwThreadId); //暫停態(tài)線程
::SetThreadPriority(h[0],THREAD_PRIORITY_IDLE); //優(yōu)先級(jí)(空閑)
::ResumeThread(h[0]);
h[1]=::CreateThread(NULL,0,ThreadNormal,NULL,0,&dwThreadId); //默認(rèn)的Normal
::WaitForMultipleObjects(2,h,TRUE,INFINITE); //等待多線程結(jié)束
::CloseHandle(h[0]);
::CloseHandle(h[1]);
return 0;
}
線程同步
多個(gè)線程同時(shí)訪問(wèn)一段數(shù)據(jù),會(huì)產(chǎn)生奇怪的問(wèn)題,由此引入臨界區(qū)
可把注釋部分刪除觀察現(xiàn)象
#include <windows.h>
#include <stdio.h>
#include <process.h>
int g_nCount1=0;
int g_nCount2=0;
BOOL g_bContinue=TRUE;
CRITICAL_SECTION g_cs;
UINT _stdcall ThreadFunc(LPVOID);
int main(int argc,char* argv[])
{
UINT uId;
HANDLE h[2];
::InitializeCriticalSection(&g_cs); //臨界區(qū)聲明
h[0]=(HANDLE)::_beginthreadex(NULL,0,ThreadFunc,NULL,0,&uId);
h[1]=(HANDLE)::_beginthreadex(NULL,0,ThreadFunc,NULL,0,&uId);
Sleep(1000);
g_bContinue=FALSE;
::WaitForMultipleObjects(2,h,TRUE,INFINITE);
::CloseHandle(h[1]);
::CloseHandle(h[2]);
::DeleteCriticalSection(&g_cs); 刪除臨界區(qū)
printf("gCount1= %d\n",g_nCount1);
printf("gCount2= %d\n",g_nCount2);
return 0;
}
UINT _stdcall ThreadFunc(LPVOID)
{
while(g_bContinue)
{
::EnterCriticalSection(&g_cs); //進(jìn)入臨界區(qū)
g_nCount1++;
g_nCount2++;
::LeaveCriticalSection(&g_cs); //離開(kāi)臨界區(qū)
}
return 0;
}