⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mymutex.cpp

📁 Visual C++高级编程及其项目应用开发(含源代码)
💻 CPP
字号:
// MyMutex.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "MyMutex.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;

int iCounter=0;

DWORD threadA(void* pD)
{
	int iID=(int)pD;
	//在内部重新打开
	//HANDLE hCounterIn=OpenMutex(MUTEX_ALL_ACCESS,FALSE,"My Try");

	CMutex g_Mutex(FALSE,"MyMutex");
	for(int i=0;i<8;i++)
	{
		printf("%d wait for object\n",iID);
		//WaitForSingleObject(hCounterIn,INFINITE);
		g_Mutex.Lock();
		Sleep(100);
		iCounter++;
		printf("\t\tthread %d : %d\n",iID,iCounter);
		//ReleaseMutex(hCounterIn);
		g_Mutex.Unlock();
	}
	//CloseHandle(hCounterIn);
	return 0;
}

void main()
{
	//创建互斥量
	//HANDLE hCounter=NULL;
	//if( (hCounter=OpenMutex(MUTEX_ALL_ACCESS,FALSE,"My Try"))==NULL)
	//{
		//如果没有其他进程创建这个互斥量,则重新创建
	//	hCounter = CreateMutex(NULL,FALSE,"My Try");
	//}

	//创建线程
	HANDLE hThread[3];
	CWinThread* pT1=AfxBeginThread((AFX_THREADPROC)threadA,(void*)1);
	CWinThread* pT2=AfxBeginThread((AFX_THREADPROC)threadA,(void*)2);
	CWinThread* pT3=AfxBeginThread((AFX_THREADPROC)threadA,(void*)3);
	hThread[0]=pT1->m_hThread;
	hThread[1]=pT2->m_hThread;
	hThread[2]=pT3->m_hThread;
	//等待线程结束
	WaitForMultipleObjects(3,hThread,TRUE,INFINITE);

	//关闭句柄
	//CloseHandle(hCounter);
}

/*

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
	int nRetCode = 0;

	// 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;
	}

	return nRetCode;
}
*/


⌨️ 快捷键说明

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