logqueue.h

来自「看到联通的接口协议的dll没」· C头文件 代码 · 共 105 行

H
105
字号

#ifndef LOGQUEUE_H
#define LOGQUEUE_H


/*
  日志队列
  采用list 就已经足够了。
  
	采用信号灯模式获取资源,当信号灯
*/
class LOGQueue{
public:	
	LOGQueue(UINT limit)
	{
		handles[SemaphoreIndex] = ::CreateSemaphore(NULL,  // no security attributes
			0,     // initial count
			limit, // max count
			NULL); // anonymous
		
		handles[StopperIndex] = ::CreateEvent(NULL,        // no security attributes
			TRUE,        // manual reset
			FALSE,       // initially non-signaled
			NULL);       // anonymous
		
		::InitializeCriticalSection(&lock);
	}
	

	~LOGQueue()
	{
		::CloseHandle(handles[SemaphoreIndex]);
		::CloseHandle(handles[StopperIndex]);
		::DeleteCriticalSection(&lock);
	}
		
	BOOL AddTail(CString p)
	{ 
		BOOL result;
		::EnterCriticalSection(&lock);
		queue.AddTail(p);
		result = ::ReleaseSemaphore(handles[SemaphoreIndex], 1, NULL);  //释放资源,打开信号灯
		
		if(!result)
		{		
			// caller can use ::GetLastError to determine what went wrong
			queue.RemoveTail();
		} 
		::LeaveCriticalSection(&lock);
		
		return result;
	} 	
	


	CString RemoveHead()
	{ 
		CString result = _T("");
		
		//其中一当有字符串加入时,就处理吐出头部列表
		switch(::WaitForMultipleObjects(2, handles, FALSE, INFINITE))
		{ 
			/* decode */
	       case StopperIndex:   // shut down thread
			   ::ExitThread(10);  // kill thread
			   return result;      // return keeps C compiler happy
			   
		   case SemaphoreIndex: 
			   // semaphore
			   ::EnterCriticalSection(&lock);
			   result = queue.RemoveHead();
			   ::LeaveCriticalSection(&lock);
			   return result;
			   
		   case WAIT_TIMEOUT: // not implemented
		   default:
			   ASSERT(FALSE); // impossible condition
			   return result;
		} 
	} 
		
	void shutdown()
	{
		::SetEvent(handles[StopperIndex]);
	}
	
	bool IsEmpty()
	{
		if (queue.IsEmpty())
			return true;
		
		return false;
   }
	   
protected:
	enum {
		StopperIndex, 
		SemaphoreIndex
	};
	
	HANDLE handles[2];
	CRITICAL_SECTION lock;
	CList<CString, CString&> queue;
};
#endif

⌨️ 快捷键说明

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