欢迎来到天天文库
浏览记录
ID:42506116
大小:89.00 KB
页数:8页
时间:2019-09-16
《实验4线程的互斥》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、实验4线程的互斥1、熟悉掌握Windows系统环境下线程的创建与撤销。2、熟悉Windows系统提供的线程互斥API。3、使用Windows系统提供的线程互斥API解决实际问题。二、实验内容和要求完成两个线程之间的互斥。在主线程中使用系统调用CreateThread()创建两个子线程,并使两个子线程互斥地使用全局变量counto#inelude"stdafx.h〃ttinclude〃5.h〃Sifdef_DEBUG#definenewDEBUG_NEWttundefTHISFILEstaticch
2、arTHISFILE[]=_FILEttendif///////////////////////////////////////////////////////////////////////////////TheoneandonlyapplicationobjectCWinAppLheApp;usingnamespacestd;staticintcount=5;staticHANDLEhl;staticHANDLEh2;LPCRIT1CAL_SECT1ONhCriticalSection;CRI
3、TICALSECTIONCritical;voidfuncl();voidfunc2();inttmain(intargc,TCHAR*argv[],TCHAR*cnvp[]){intnRetCode二0;DWORDdwThreadlDl,dwThreadlD2;hCriticalScction=&Critical;InitializeCriticalSection(hCriticalSection);hl^CreateThread((LPSECURITY_ATTRIBUTES)NULL,0,(L
4、PTHREADSTARTROUTINE)fund,(LPVOID)NULL,0,ftdwThreadlDl);if(hl==NULL)printf(,zThreadlcreateFail!?/);elseprintfC'ThrcadlcreateSuccess!z,);h2=CreateThread((LPSECURITY_ATTRIBUTES)NULL,(LPTHREADSTARTROUTINE)func2,(LPVOID)NULL,0,&dwThreadID2);if(h2==NULL
5、)printf(,zThread2createFail!/z);elseprintf(z,Thrcad2createSuccess!z,);Sleep(lOOO);CloseHandle(hl);CloseHandle(h2);DclctcCriticalScction(hCriticalScction);ExitThread(0);returnnRetCode;}voidfunc2()intr2;EnLerCriticalSection(hCriticalSection);r2二coun
6、t;sleep(lOO);r2=r2+l;count二r2;printf(〃countinfunc2=%dcount);LeaveCriticalSection(hCriticalSection);}voidfund()!intrl;EntcrCriticalSection(hCriticalScction);rl二count;_sleep(500);rl=rl+l;count=rl;printf(〃countinfuncl=%d,count);LeaveCriticalSection(hCr
7、iticalSection);wD:vc6.0MicrosoftVisualStudioMyProjects5Debug5.exeRThreadlcreateSuccess?Thread2createSuccess?countinfund=6countinfunc2=7Pressanykeytocontinue//5.cpp:DefinestheentrypointFortheconsoleapplication.二剧5classes-匕IGlobals•_tma•func'•fund
8、(/CriticQhCritOtheA
9、■^cJ^irIdr^include,,stdafx.hi,ttinclude"S.h"ttifdef_DEBUGttdefinenewDEB也NEWttundefTHIS^FILEstaticcharTHIS_FILE[]=_FILE_;ttendif///////////////////////////////////////////////////////////////////////////////Theoneandonlyappl
此文档下载收益归作者所有