common.cpp

来自「基于windows mfc的多线程程序设计之赛马进度条的显示」· C++ 代码 · 共 73 行

CPP
73
字号
#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;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?