📄 semaphore.cpp
字号:
// Semaphore.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "Semaphore.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
static int count=1;
static HANDLE h1;
static HANDLE h2;
static HANDLE hHandle1=NULL;
void func1();
void func2();
/////////////////////////////////////////////////////////////////////////////
// The one and only application object
CWinApp theApp;
using namespace std;
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
DWORD dwThreadID1,dwThreadID2;
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,"SemaphoreName1");
if (hHandle1==NULL) printf("Semaphore Open Fail!\n");
else printf("Semaphore Open Success!\n");
// initialize MFC and print and error on failure
/* if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
cerr << _T("Fatal Error: MFC initialization failed") << endl;
nRetCode = 1;
}
else
{
// TODO: code your application's behavior here.
CString strHello;
strHello.LoadString(IDS_HELLO);
cout << (LPCTSTR)strHello << endl;
}
*/
h1=CreateThread((LPSECURITY_ATTRIBUTES)NULL,
0,
(LPTHREAD_START_ROUTINE)func1,
(LPVOID)NULL,
0,&dwThreadID1);
if (h1==NULL) printf("Thread1 create Fail!\n");
else printf("Thread1 create Success!\n");
h2=CreateThread((LPSECURITY_ATTRIBUTES)NULL,
0,
(LPTHREAD_START_ROUTINE)func2,
(LPVOID)NULL,
0,&dwThreadID2);
if (h2==NULL) printf("Thread2 create Fail!\n");
else printf("Thread2 create Success!\n");
_sleep(1000);
printf("Thread Finished!\n");
CloseHandle(h1);
CloseHandle(h2);
CloseHandle(hHandle1);
ExitThread(0);
return nRetCode;
}
void func1()
{
DWORD dRes,err;
dRes=WaitForSingleObject(hHandle1,INFINITE);
err=GetLastError();
printf("WaitForSingleObject err=%d\n",err);
if (dRes == WAIT_TIMEOUT) printf("TIMEOUT!dRes=%d\n",dRes);
else if (dRes == WAIT_OBJECT_0) printf("WAIT_OBJECT!dRes=%d\n",dRes);
else if (dRes == WAIT_ABANDONED) printf("WAIT_ABANDONED!dRes=%d\n",dRes);
else printf("dRes=%d\n",dRes);
printf("count in func1=%d\n",count);
}
void func2()
{
BOOL rc;
DWORD err;
count=5;
printf("count in func2=%d\n",count);
rc=ReleaseSemaphore(hHandle1,1,NULL);
err=GetLastError();
printf("ReleaseSemaphore err=%d\n",err);
if (rc==0) printf("Semaphore Release Fail!\n");
else printf("Semaphore Release Success!rc=%d\n",rc);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -