分类:
2009-09-27 11:15:58
CSemaphore 类的构造函数原型及参数说明如下:
CSemaphore (LONG lInitialCount=1, LONG lMaxCount=1, LPCTSTR pstrName=NULL, LPSECURITY_ATTRIBUTES lpsaAttributes=NULL);
CSemaphore Semaphore(2,2);可以在类的构造函数中动态地创建CSemaphore对象,如:
Semaphore=new CSemaphore(2,2);信号量CSemaphore被建立后,就可以准备用它来对共享资源进行访问计数。要完成计数处理,首先应建立一个CSingleLock或CMultiLock对象,如:
CSingleLock SingleLock(Semaphore);要减小这个信号Semaphore的计数值,只须调用CSingleLock对象的成员函数Lock()即可:
SingleLock.Lock();同样,通过调用UnLock()来释放这个信号量,即:
SingleLock.UnLock();从而我们可这样来申明类:
#include "afxmt.h" class CSharedResource { private: CSemaphore* ptrSemaphore; public: CSharedResource(); ~CSharedResource(); void AccessResource(); };在构造函数中完成对信号对象的创建:
CSharedResource::CSharedResource() { ptrSemaphore=new CSemaphore(2,2); }在析构函数中完成对信号对象的释放:
CSharedResource::~CSharedResource() { delete ptrSemaphore; }用以下过程来访问共享资源:
void CSharedResource::AccessResource() { CSingleLock SingleLock(ptrSemaphore); SingleLock.Lock(); /* ...... 资源访问 */ Sleep(1000); }再建立使用信号量的线程函数:
UINT Thread_Proc1(LPVOID param) { SharedResource.AccessResource(); ::MessageBox((HWND)param,"Thread #1 had accessed the Semaphore!","Thread Proc1",MB_OK); return 0; } UINT Thread_Proc2(LPVOID param) { SharedResource.AccessResource(); ::MessageBox((HWND)param,"Thread #2 had accessed the Semaphore!","Thread Proc2",MB_OK); return 0; } UINT Thread_Proc3(LPVOID param) { SharedResource.AccessResource(); ::MessageBox((HWND)param,"Thread #3 had accessed the Semaphore!","Thread Proc3",MB_OK); return 0; }再用以下代码执行各个线程函数:
HWND hWnd=GetSafeHwnd(); AfxBeginThread(Thread_Proc1,hWnd); AfxBeginThread(Thread_Proc2,hWnd); AfxBeginThread(Thread_Proc3,hWnd);这样当Thread_Proc1和Thread_Proc2占用信号量之后,只有等其中一个释放信号量之后,Thread_Proc3方可占用信号量,达到了线程之间资源的保护,实现数据共享!