www.pudn.com > 2003090514065121890.zip > lockTest.cpp


// lockTest.cpp : Defines the entry point for the console application. 
// 
 
#include "stdafx.h" 
#include "lockTest.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; 
 
CSingleAccessLock glo_lock("test"); 
int glo_iLock=0; 
CRWAccessLock glo_rw("test"); 
int glo_iRW=0; 
 
DWORD TestThread_rw(LPVOID pD) 
{ 
	for(int i=0;i<90000;i++) 
	{ 
		int iGet=0; 
		glo_rw.Access(); 
		iGet = glo_iRW ++; 
		glo_rw.LeaveAccess(); 
 
		if(iGet %1000 ==0 ) 
			printf("\t\tReadWrite Lock = %d\n",iGet); 
 
		glo_rw.Visit(); 
		iGet = glo_iRW; 
		glo_rw.LeaveVisit(); 
 
		glo_rw.Visit(); 
		iGet = glo_iRW; 
		glo_rw.LeaveVisit(); 
 
		glo_rw.Visit(); 
		iGet = glo_iRW; 
		glo_rw.LeaveVisit(); 
	} 
	return 0; 
} 
 
DWORD TestThread_mutex(LPVOID pD) 
{ 
	for(int i=0;i<90000;i++) 
	{ 
		int iGet=0; 
		glo_lock.Access(); 
		iGet = glo_iLock ++; 
		glo_lock.LeaveAccess(); 
 
		if(iGet %1000 ==0 ) 
			printf("\tMutex Lock = %d\n",iGet); 
		 
		glo_lock.Visit(); 
		iGet = glo_iLock; 
		glo_lock.LeaveVisit(); 
		 
		glo_lock.Visit(); 
		iGet = glo_iLock; 
		glo_lock.LeaveVisit(); 
		 
		glo_lock.Visit(); 
		iGet = glo_iLock; 
		glo_lock.LeaveVisit(); 
	} 
	return 0; 
} 
 
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) 
{ 
	int nRetCode = 0; 
	HANDLE hThread[20]; 
 
	// 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 
	{ 
		DWORD dwID,dwT1,dwT2,dwT3; 
		int i; 
		dwT1 = GetTickCount(); 
		for(i=0;i<20;i++) 
		{ 
			hThread[i] = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)TestThread_mutex,NULL,0,&dwID); 
		} 
		WaitForMultipleObjects(20,hThread,TRUE,INFINITE); 
		dwT2 = GetTickCount(); 
		for(i=0;i<20;i++) 
		{ 
			hThread[i] = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)TestThread_rw,NULL,0,&dwID); 
		} 
		WaitForMultipleObjects(20,hThread,TRUE,INFINITE); 
		dwT3 = GetTickCount(); 
 
		printf("\n\n rw = %d\n mutex = %d\nOver\n",dwT2-dwT1,dwT3-dwT2); 
	} 
 
	return nRetCode; 
}