// testWinLock.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "LockMutex.h"
#include "CriSection.h"
#include <iostream>
#include <process.h>
#include <time.h>
using namespace std;
//#define ENABLE_MUTEX
#define ENABLE_CRITICAL_SECTION
#if defined (ENABLE_MUTEX)
//创建一个互斥对象类型锁
CLockMutex g_Lock;
#elif defined (ENABLE_CRITICAL_SECTION)
//创建一个临界区类型锁
CCriSection g_Lock;
#endif
void LockCompare(int &iNum)
{
CMyLock lock1(g_Lock);//线程所有权判断,同线程可访问
//g_Lock.Lock();
cout<<"+";
iNum++;
//g_Lock.Unlock();
}
//线程函数
unsigned int __stdcall StartThread(void *pParam)
{
char *pMsg = (char *)pParam;
if (!pMsg)
{
return (unsigned int)1;
}
cout<<"============="<<pMsg<<endl;
CMyLock lock2(g_Lock);
//g_Lock.Lock();
cout<<"============="<<pMsg<<"locked"<<endl;
clock_t tStart,tEnd;
tStart = clock();
int iNum = 0;
for (int i = 0; i < 100; i++)
{
LockCompare(iNum);
}
tEnd = clock();
#if defined (ENABLE_MUTEX)
cout<<"The lock type is mutex, time = "<<(tEnd - tStart)<<" ms."<<endl;
#elif defined (ENABLE_CRITICAL_SECTION)
cout<<"The lock type is critical section, time = "<<(tEnd - tStart)<<" ms."<<endl;
#endif
//g_Lock.Unlock();
return (unsigned int)0;
}
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hThread1, hThread2;
unsigned int uiThreadId1, uiThreadId2;
char *pMsg1 = "First print thread.";
char *pMsg2 = "Second print thread.";
//创建两个工作线程,分别打印不同的消息
hThread1 = (HANDLE)_beginthreadex(NULL, 0, &StartThread, (void *)pMsg1, 0, &uiThreadId1);
hThread2 = (HANDLE)_beginthreadex(NULL, 0, &StartThread, (void *)pMsg2, 0, &uiThreadId2);
//等待线程结束
DWORD dwRet = WaitForSingleObject(hThread1,INFINITE);
if ( dwRet == WAIT_TIMEOUT )
{
TerminateThread(hThread1,0);
}
dwRet = WaitForSingleObject(hThread2,INFINITE);
if ( dwRet == WAIT_TIMEOUT )
{
TerminateThread(hThread2,0);
}
//关闭线程句柄,释放资源
::CloseHandle(hThread1);
::CloseHandle(hThread2);
system("pause");
return 0;
}