一、实验目的
1、掌握Windows系统环境下线程的创建与撤销。 2、熟悉Windows系统提供的线程同步API。
3、使用Windows系统提供的线程同步API解决实际问题。
二、实验内容和要求
(1)使用系统调用CreateThread()创建一个子线程,并在线程中显示:Thread is Running!。为了能让用户清楚地看到线程的运行情况,使用Sleep()使线程挂起5秒,之后使用ExitThread()撤销进程。
(2)完成主、子两个线程之间的同步,要求子线程先执行。在主线程中使用系统调用CreateThread()创建一个子线程。主线程创建子线程后进入阻塞状态,直到子线程运行完毕后唤醒主线程。
// 20142204.cpp : Defines the entry point for the console application. //
#include \"stdafx.h\" #include \"20142204.h\"
#ifdef _DEBUG
#define new DEBUG_NEW #undef THIS_FILE
static char THIS_FILE[] = __FILE__; #endif
///////////////////////////////////////////////////////////////////////////// // The one and only application object
CWinApp theApp;
using namespace std;
static HANDLE h1;
static HANDLE hHandle1=NULL;
void func();
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) {
int nRetCode = 0;
DWORD dwThreadID1; DWORD dRes,err;
hHandle1=CreateSemaphore(NULL,0,1,\"SemaphoreName1\"); if(hHandle1==NULL)printf(\"Semaphore Create Fail!\\n\"); else printf(\"Semaphore Create Success!\\n\");
hHandle1=OpenSemaphore(SYNCHRONIZE|SEMAPHORE_MODIFY_STATE, NULL,
\"SemapgoreName1\");
if(hHandle1==NULL)printf(\"Semaphore Create Fail!\\n\"); else printf(\"Semaphore Create Success!\\n\"); h1=CreateThread((LPSECURITY_ATTRIBUTES)NULL, 0,
(LPTHREAD_START_ROUTINE)func, (LPVOID)NULL, 0,&dwThreadID1);
if(h1==NULL)printf(\"Thread1 Create Fail!\\n\"); else printf(\"Thread1 Create Success!\\n\"); dRes=WaitForSingleObject(hHandle1,INFINITE); err=GetLastError();
printf(\"WaitForSingleObject err=%d\\n\
if(dRes==WAIT_TIMEOUT) printf(\"TIMEOUT!dRes=%d\\n\
else if (dRes==WAIT_OBJECT_0) printf(\"WAIT_OBJECT!dRes=%d\\n\ else if (dRes==WAIT_ABANDONED)
printf(\"WAIT_ABANDONED!dRes=%d\\n\ else printf(\"dRes=%d\\n\
CloseHandle(h1);
CloseHandle(hHandle1); ExitThread(0);
return nRetCode; }
void func() {
BOOL rc; DWORD err;
printf(\"Now In Thread!\\n\");
rc=ReleaseSemaphore(hHandle1,1,NULL); err=GetLastError();
printf(\"ReleaseSemaphore err=%d\\n\
if(rc==0)printf(\"Semaphore Release Fail!\\n\");
else printf(\"Semaphore Release Success!rc=%d\\n\}
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- ovod.cn 版权所有 湘ICP备2023023988号-4
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务