www.pudn.com > Racing.rar > Common.cpp


#include "stdafx.h" 
#include "Common.h" 
 
 
// Mutex对象的名称 
char g_strRName[64] = "RedHorse"; 
char g_strGName[64] = "GreenHorse"; 
char g_strBName[64] = "BlueHorse"; 
 
// Mutex对象的句柄 
HANDLE g_hRMutex; 
HANDLE g_hGMutex; 
HANDLE g_hBMutex; 
 
extern DWORD WINAPI ThreadProc(LPVOID lpParam) 
{ 
	LPHORSE	 lpHorse; 
	HANDLE 	 hMutex; 
	 
	lpHorse = LPHORSE(lpParam); 
 
	// 打开Mutex对象 
	if( lpHorse->color == RED ) 
	{ 
		hMutex = ::OpenMutex(MUTEX_ALL_ACCESS, FALSE, g_strRName); 
	} 
 
	else if ( lpHorse->color == GREEN ) 
	{ 
		hMutex = ::OpenMutex(MUTEX_ALL_ACCESS, FALSE, g_strGName); 
	} 
 
	else if ( lpHorse->color == BLUE ) 
	{ 
		hMutex = ::OpenMutex(MUTEX_ALL_ACCESS, FALSE, g_strBName); 
	} 
 
	else 
		return 1;	// 颜色不对 
 
	if( hMutex == NULL ) 
	{ 
		AfxMessageBox("open mutex error..."); 
		return 1; 
	} 
 
	// 循环,等待信号 
	while ( true ) 
	{ 
		if ( WaitForSingleObject(hMutex, INFINITE) == WAIT_FAILED ) 
		{ 
			continue; 
		} 
 
		// 马前进 
		if ( lpHorse->x < lpHorse->rect.right ) 
		{ 
			lpHorse->x ++; 
		} 
 
		// 重绘窗口 
		InvalidateRect(lpHorse->hWnd, lpHorse->rect, TRUE); 
		 
		// 释放Mutex 
		ReleaseMutex(hMutex); 
 
		// 等待, 速度快的等待时间短 
		Sleep(lpHorse->speed); 
	} 
 
	return 0; 
}