return0;
}
3线程管理实例1
#include"stdafx.h"
#include
#include
usingnamespacestd;
DWORDWINAPIFunOne(LPVOIDparam){
while(true)
{
Sleep(1000);
cout<<"hello!
";
}
return0;
}
DWORDWINAPIFunTwo(LPVOIDparam){
while(true)
{
Sleep(1000);
cout<<"world!
";
}
return0;
}
intmain(intargc,char*argv[])
{
intinput=0;
DWORDlp1=0,lp2=0;
HANDLEhand1=CreateThread(NULL,0,FunOne,(void*)&input,CREATE_SUSPENDED,&lp1);
HANDLEhand2=CreateThread(NULL,0,FunTwo,(void*)&input,CREATE_SUSPENDED,&lp2);
while(true){
cin>>input;
if(input==1)
{
ResumeThread(hand1);
ResumeThread(hand2);
}
if(input==2)
{
SuspendThread(hand1);
SuspendThread(hand2);
}
if(input==0)
{
TerminateThread(hand1,1);
TerminateThread(hand2,1);
}
if(input==9)
return0;
};
return0;
}
线程管理实例2——在主线程中创建一个线程中通过自增对Counter计数到1000000,主线程一直等待其结束:
#include"stdafx.h"
#include
#include
#include
#include
unsignedCounter;
unsigned__stdcallSecondThreadFunc(void*pArguments){
printf("Insecondthread...\n");
while(Counter<1000000)
Counter++;
_endthreadex(0);
return0;
}
intmain(){
HANDLEhThread;
unsignedthreadID;
printf("Creatingsecondthread...\n");
//Createthesecondthread.
hThread=(HANDLE)_beginthreadex(NULL,0,&SecondThreadFunc,NULL,0,
&threadID);
//Waituntilsecondthreadterminates
WaitForSingleObject(hThread,INFINITE);
printf("Countershouldbe1000000;itis->%d\n",Counter);
//Destroythethreadobject.
CloseHandle(hThread);
}
线程管理实例2——主线程通过GetExitCodeThread来判断两个线程是否结束运行:
#include"stdafx.h"
#include
#include
#include
#include
#include
/*
*Takethestartupvalue,dosomesimplemathonit,
*andreturnthecalculatedvalue.
*/
DWORDWINAPIThreadFunc(LPVOIDn){
Sleep((DWORD)n*1000*2);
return(DWORD)n*10;
}
intmain(){
HANDLEhThrd1;
HANDLEhThrd2;
DWORDexitCode1=0;
DWORDexitCode2=0;
DWORDthreadId;
hThrd1=CreateThread(NULL,0,ThreadFunc,(LPVOID)1,0,&threadId);
if(hThrd1)
printf("Thread1launched\n");
hThrd2=CreateThread(NULL,0,ThreadFunc,(LPVOID)2,0,&threadId);
if(hThrd2)
printf("Thread2launched\n");
//KeepwaitinguntilbothcallstoGetExitCodeThreadsucceedAND
//neitherofthemreturnsSTILL_ACTIVE.
for(;;){
printf("Pressanykeytoexit..\n");
_getch();
GetExitCodeThread(hThrd1,&exitCode1);
GetExitCodeThread(hThrd2,&exitCode2);
if(exitCode1==STILL_ACTIVE)
puts("Thread1isstillrunning!
");
if(exitCode2==STILL_ACTIVE)
puts("Thread2isstillrunning!
");
if(exitCode1!
=STILL_ACTIVE&&exitCode2!
=STILL_ACTIVE)
break;
}
CloseHandle(hThrd1);
CloseHandle(hThrd2);
printf("Thread1returned%d\n",exitCode1);
printf("Thread2returned%d\n",exitCode2);
returnEXIT_SUCCESS;
}
线程管理实例3——多线程程序运行顺序的不可预料:
#include"stdafx.h"
#include
#include
#include
#include
DWORDWINAPIThreadFunc(LPVOIDn){
inti;
for(i=0;i<10;i++)
printf("%d%d%d%d%d%d%d%d\n",n,n,n,n,n,n,n,n);
return0;
}
intmain(){
HANDLEhThrd;
DWORDthreadId;
inti;
for(i=0;i<5;i++){
hThrd=CreateThread(NULL,0,ThreadFunc,(LPVOID)i,0,&threadId);
if(hThrd){
printf("Threadlaunched%d\n",i);
CloseHandle(hThrd);
}
}
//Waitforthethreadstocomplete.
Sleep(2000);
returnEXIT_SUCCESS;
}
4同步——全局变量
#include"stdafx.h"
#include
#include
usingnamespacestd;
intglobalvar=false;
DWORDWINAPIThreadFunc(LPVOIDpParam)
{
cout<<"ThreadFunc"<Sleep(200);
globalvar=true;
return0;
}
intmain()
{
HANDLEhthread=CreateThread(NULL,0,ThreadFunc,NULL,0,NULL);
if(!
hthread)
{
cout<<"ThreadCreateError!
"<CloseHandle(hthread);
}
while(!
globalvar)
cout<<"Threadwhile"<cout<<"Threadexit"<return0;
}
5事件机制应用实例
#include"stdafx.h"
#include
#include
#include
#include
usingnamespacestd;
HANDLEevRead,evFinish;
voidReadThread(LPVOIDparam)
{
WaitForSingleObject(evRead,INFINITE);
cout<<"Reading"<SetEvent(evFinish);
}
voidWriteThread(LPVOIDparam)
{
cout<<"Writing"<SetEvent(evRead);
}
intmain(intargc,char*argv[])
{
evRead=CreateEvent(NULL,FALSE,FALSE,NULL);
evFinish=CreateEvent(NULL,FALSE,FALSE,NULL);
_beginthread(ReadThread,0,NULL);
_beginthread(WriteThread,0,NULL);
WaitForSingleObject(evFinish,INFINITE);
cout<<"TheProgramisEnd"<return0;
}
6临界区同步机制实例
#include"stdafx.h"
#include
#include
#include
#include
usingnamespacestd;
inttotal=100;
HANDLEevFin[2];
CRITICAL_SECTIONcs;
voidWithdrawThread1(LPVOIDparam)
{
EnterCriticalSection(&cs);
if(total-90>=0)
{
total-=90;
cout<<"Youwithdraw90"<}
else
cout<<"Youdonothavethatmuchmoney"<LeaveCriticalSection(&cs);
SetEvent(evFin[0]);
}
voidWithdrawThread2(LPVOIDparam)
{
EnterCriticalSection(&cs);
if(total-20>=0)
{
total-=20;
cout<<"Youwithdraw20"<}
else
cout<<"Youdonothavethatmuchmoney"<LeaveCriticalSection(&cs);
SetEvent(evFin[1]);
}
intmain(intargc,char*argv[])
{
evFin[0]=CreateEvent(NULL,FALSE,FALSE,NULL);
evFin[1]=CreateEvent(NULL,FALSE,FALSE,NULL);
InitializeCriticalSection(&cs);
_beginthread(WithdrawThread1,0,NULL);
_beginthread(WithdrawThread2,0,NULL);
WaitForMultipleObjects(2,evFin,TRUE,INFINITE);
DeleteCriticalSection(&cs);
cout<return0;
}
6临界区同步机制实例——潜在的死锁问题
#include"stdafx.h"
#include
#include
#include
CRITICAL_SECTIONcs1,cs2;
longWINAPIThreadFn(longlParam)
{
while(TRUE){
EnterCriticalSection(&cs2);
printf("\n线程2占用临界区2");
EnterCriticalSection(&cs1);
printf("\n线程2占用临界区1");
printf("\n线程2占用两个临界区");
LeaveCriticalSection(&cs1);
LeaveCriticalSection(&cs2);
printf("\n线程2释放两个临界区");
Sleep(20);
}
}
intmain(intargc,char*argv[]){
DWORDiThreadID;
InitializeCriticalSection(&cs1);
InitializeCriticalSection(&cs2);
CloseHandle(CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadFn,
NULL,0,&iThreadID));
while(TRUE){
EnterCriticalSection(&cs1);
printf("\n线程1占用临界区1");
EnterCriticalSection(&cs2);
printf("\n线程1占用临界区2");
printf("\n线程1占用两个临界区");
LeaveCriticalSection(&cs2);
LeaveCriticalSection(&cs1);
printf("\n线程1释放两个临界区");
Sleep(20);
};
return(0);
}
7互斥量同步机制实例
VC6与VS2003等默认使用ANSI编码,而VS2005默认采用Unicode
进入工程属性设置菜单。
选择configurationproperties-->General-->在左边projectdefault中characterset中设置notset。
#include"stdafx.h"
#include
#include
#defineTHREAD_INSTANCE_NUMBER3
usingnamespacestd;
LONGg_fResourceInUse=FALSE;
LONGg_lCounter=0;
DWORDThreadProc(void*pData){
intThreadNumberTemp=(*(int*)pData);
HANDLEhMutex;
if((hMutex=OpenMutex(MUTEX_ALL_ACCESS,FALSE,"Mutex.Test"))==NULL){
cout<<"OpenMutexerror!
"<}
WaitForSingleObject(hMutex,INFINITE);
cout<<"ThreadProc:
"<"<cout<<"ThreadProc"<ReleaseMutex(hMutex);
CloseHandle(hMutex);
return0;
}
intmain(intargc,char*argv[])
{
inti;
DWORDID[THREAD_INSTANCE_NUMBER];
HANDLEh[THREAD_INSTANCE_NUMBER];
HANDLEhMutex;
if((hMutex=OpenMutex(MUTEX_ALL_ACCESS,FALSE,"Mutex.Test"))==NULL){
if((hMutex=CreateMutex(NULL,FALSE,"Mutex.Test"))==NULL){
cout<<"CreateMutexerror!
"<return0;
}
}
for(i=0;i{
WaitForSingleObject(hMutex,INFINITE);
h[i]=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadProc,(void*)&ID[i],0,&(ID[i]));
if(h[i]==NULL)
cout<<"CreateThreaderror"<else
cout<<"CreateThread:
"<ReleaseMutex(hMutex);
}
WaitForMultipleObjects(THREAD_INSTANCE_NUMBER,h,TRUE,INFINITE);
cout<<"ClosetheMutexHandle!
"<CloseHandle(hMutex);
system("pause");
return0;
}
8信号量同步机制实例1
#include"stdafx.h"
#include
#include
usingnamespacestd;
#defineTHREAD_INSTANCE_NUMBER3
DWORDfoo(void*pData){
intThreadNumberTemp=(*(int*)pData);
HANDLEhSemaphore;
if((hSemaphore=OpenSemaphore(SEMAPHORE_ALL