利用多线程同步互斥来创建自己的资源锁

#include <Windows.h>

#include <iostream>

using namespace std;





class CMyLock 

{

public:

	CMyLock();

	~CMyLock();



public:

	bool Lock();

	bool UnLock();



private: 

	HANDLE hEvent;

};



CMyLock::CMyLock()

{



}



CMyLock::~CMyLock()

{

	CloseHandle(hEvent);
}



bool CMyLock::Lock()

{

	hEvent =  OpenEvent(EVENT_ALL_ACCESS,TRUE,L"GaoHanEvent");

	if (hEvent)

	{

		WaitForSingleObject(hEvent,INFINITE);

	}

	else

	{

		hEvent = CreateEvent(NULL,TRUE,TRUE,L"GaoHanEvent");

		SetEvent(hEvent);

	}

	ResetEvent(hEvent);

	return TRUE;

}



bool CMyLock::UnLock()

{

	SetEvent(hEvent);

	return TRUE;

}





CMyLock lock;

DWORD WINAPI SonThreadFun( LPVOID lpThreadParameter );



int main()

{



	HANDLE hThread = CreateThread(NULL,0,SonThreadFun,NULL,CREATE_ALWAYS,NULL);

	if (!hThread)

	{

		return 0;

	}

	Sleep(1000);

	lock.Lock();

	cout<<"The Father Play Roles"<<endl;

	lock.UnLock();



	WaitForSingleObject(hThread,INFINITE);



	return 0;

}



DWORD WINAPI SonThreadFun( LPVOID lpThreadParameter )

{

	lock.Lock();

	cout<<"The Son Play Roles"<<endl;

	Sleep(10000);

	lock.UnLock();

	return 0;

}

  说明:这是Windows下,利用Event(事件)来创建一个锁。这个锁能够防止访问的冲突。

#include <iostream>

#include <Windows.h>

using namespace std;



class CLock

{

public:

	CLock():hd(NULL){}

	~CLock(){CloseHandle(hd);

	}



public:

	bool Lock()

	{

		hd = OpenMutex(MUTEX_ALL_ACCESS,TRUE,L"GaoHanMutex");

		if (hd)

		{

			WaitForSingleObject(hd,INFINITE);

		}

		else

		{

			hd = CreateMutex(NULL,TRUE,L"GaoHanMutex");

		}



		return true;

	}

	bool unLock()

	{

		if (hd)

			ReleaseMutex(hd);

		return true;

	}

private:

	HANDLE hd;

};



CLock lock;

DWORD WINAPI ThreadFunc( LPVOID lpThreadParameter );

int main()

{

	HANDLE  hThread = CreateThread(NULL,0,ThreadFunc,NULL,CREATE_ALWAYS,NULL);

	Sleep(1000);

	lock.Lock();

	cout<<"父进程获得机会,开始把资源锁起来"<<endl;

	lock.unLock();

	WaitForSingleObject(hThread,INFINITE);

	return 0;

}



DWORD WINAPI ThreadFunc( LPVOID lpThreadParameter )

{

	lock.Lock();

	Sleep(10000);

	cout<<"睡了10秒,现在开始工作"<<endl;

	lock.unLock();

	return 0;

}

  以上是利用事件来创建一个锁程序。该锁程序可以在同一个进程内的不同线程之间可以使用,但是对于多个进程中的不同线程,并不能起作用。


你可能感兴趣的:(线程同步)