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

📄 mutex.cpp

📁 这是操作系统的上机资料,关于线程同步和互斥的
💻 CPP
字号:
// Mutex.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "Mutex.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif


static int count=5;
static HANDLE h1;
static HANDLE h2;
LPCRITICAL_SECTION hCriticalSection;
CRITICAL_SECTION Critical;
void func1();
void func2();




/////////////////////////////////////////////////////////////////////////////
// The one and only application object

CWinApp theApp;

using namespace std;

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

	hCriticalSection=&Critical;
	InitializeCriticalSection(hCriticalSection);

	// 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;
	}
*/
	h1=CreateThread((LPSECURITY_ATTRIBUTES)NULL,
					0,
					(LPTHREAD_START_ROUTINE)func1,
					(LPVOID)NULL,
					0,&dwThreadID1);
	if (h1==NULL) printf("Thread1 create Fail!\n");
	else printf("Thread1 create Success!\n");

	h2=CreateThread((LPSECURITY_ATTRIBUTES)NULL,
					0,
					(LPTHREAD_START_ROUTINE)func2,
					(LPVOID)NULL,
					0,&dwThreadID2);
	if (h2==NULL) printf("Thread2 create Fail!\n");
	else printf("Thread2 create Success!\n");

    _sleep(1000);

	CloseHandle(h1);
	CloseHandle(h2);

	DeleteCriticalSection(hCriticalSection);
	ExitThread(0);
	return nRetCode;
}


void func2()
{
	int r2;

	EnterCriticalSection(hCriticalSection);
	r2=count;
	_sleep(100);
	r2=r2+1;
	count=r2;
	printf("count in func2=%d\n",count);
	LeaveCriticalSection(hCriticalSection);
}
void func1()
{
	int r1;

	EnterCriticalSection(hCriticalSection);
	r1=count;
	_sleep(500);
	r1=r1+1;
	count=r1;
	printf("count in func1=%d\n",count);
	LeaveCriticalSection(hCriticalSection);
}

⌨️ 快捷键说明

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