=====================================SuperMap.h============================
#ifndef _SUPER_MAP_H
#define _SUPER_MAP_H
#include "mutex.h"
#include <map>
using namespace std;
template <class CKey,class CValue,class TYPE>
class CSuperMap
{
public:
inline void Insert(CKey key,CValue* value)
{
CAutoMutex automutex(&m_mutexmap);
m_map.insert(make_pair(key,value));
}
inline void Delete(CKey key,bool bDelObj=true)
{
CAutoMutex automutex(&m_mutexmap);
typename TYPE::iterator it;
it = m_map.find(key);
if (it != m_map.end())
{
if (bDelObj)
delete it->second;//free obj memory
m_map.erase(it); //delete item from map
}
}
inline void Clear()
{
CAutoMutex automutex(&m_mutexmap);
m_map.clear();
}
inline int Size()
{
return m_map.size();
}
inline CValue* Find(CKey key,bool bLock=false)
{
typename TYPE::iterator it;
if (bLock)
{
CAutoMutex automutex(&m_mutexmap);
it = m_map.find(key);
if (it != m_map.end())
return it->second;
}
else
{
it = m_map.find(key);
if (it != m_map.end())
return it->second;
}
return NULL;
}
inline TYPE* GetMap()
{
return &m_map;
}
inline CMyMutex* GetMutex()
{
return &m_mutexmap;
}
private:
CMyMutex m_mutexmap;
TYPE m_map;
};
#endif
=================================Mutex.h=========================
#ifndef _CPS_MUTEX_H
#define _CPS_MUTEX_H
#if defined(WIN32)
#include <windows.h>
#else
#include <pthread.h>
#endif
class CMyMutex
{
public:
CMyMutex(bool lockFlag=false);
~CMyMutex();
public:
void Lock();
void UnLock();
inline int GetCount()
{
return m_count;
}
protected:
int m_count;
#ifdef WIN32
HANDLE m_mutex;
#else
pthread_mutex_t m_mutex;
#endif
};
class CAutoMutex
{
public:
inline CAutoMutex(CMyMutex* p_Mutex):m_pMutex(p_Mutex)
{
if (m_pMutex != NULL)
m_pMutex->Lock();
}
inline ~CAutoMutex()
{
if (m_pMutex != NULL)
m_pMutex->UnLock();
}
private:
CMyMutex* m_pMutex;
};
#endif
================================mutex.cpp================================
#include "mutex.h"
CMyMutex::CMyMutex(bool lockFlag):m_count(0)
{
#ifdef WIN32
// ::InitializeCriticalSection(&m_mutex);
m_mutex = CreateMutex(NULL, FALSE, NULL);
#else
(void)pthread_mutex_init(&m_mutex, NULL);
#endif
if (lockFlag)
{
this->Lock();
}
}
CMyMutex::~CMyMutex()
{
//while (this->m_count>0)
//this->UnLock();
#ifdef WIN32
//::DeleteCriticalSection(&m_mutex);
CloseHandle(m_mutex);
#else
pthread_mutex_destroy(&m_mutex);
#endif
}
void CMyMutex::Lock()
{
//m_count++;
#ifdef WIN32
//::EnterCriticalSection(&m_mutex);
switch (WaitForSingleObject(m_mutex, INFINITE)) {
case WAIT_ABANDONED:
case WAIT_TIMEOUT:
return ;
default:
break;
}
#else
pthread_mutex_lock(&m_mutex);
#endif
}
void CMyMutex::UnLock()
{
//if (m_count<=0)
// return ;
//m_count--;
#ifdef WIN32
//::LeaveCriticalSection(&m_mutex);
ReleaseMutex(m_mutex);
#else
pthread_mutex_unlock(&m_mutex);
#endif
}
===========================用法==============================
class CTest;
CTest test;
CSuperMap<string,,test,CTest> m_stringtestMap;
CTest* pTest = new CTest;
m_stringtestMap.Insert("key",pTest);