rel="File-List" href="file:///C:%5CDOCUME%7E1%5CADMINI%7E1%5CLOCALS%7E1%5CTemp%5Cmsohtml1%5C01%5Cclip_filelist.xml" />
std::list本身不具备线程安全功能,本文利用开源库boost的互斥体类mutex实现一个带互斥功能的线程安全列表模板类。
1 定义一个模板类,继承于std::list,增加boost::mutex成员变量,代码如下:
#include "list"
#include <boost/thread.hpp>
template<typename T>
class CLockList
: public std::list<T>
{
protected:
boost::mutex m_mutex;
};
2 我们主要实现add、front和clear三个函数,带互斥功能,其他功能函数可以自行添加;
add函数实现把元素添加到列表末尾,代码如下:
void add(T t)
{
boost::mutex::scoped_lock lock(m_mutex);
std::list<T>::push_back(t);
}
front函数实现取出,列表头元素,is_pop决定是否删除该元素,代码如下:
bool front(T & out, bool is_pop = true)
{
boost::mutex::scoped_lock lock(m_mutex);
typename std::list<T>::iterator pIter = std::list<T>::begin();
if (pIter == std::list<T>::end())
return false;
out = *pIter;
if (is_pop)
std::list<T>::pop_front();
return true;
}
clear函数实现清空该列表,is_lock决定是否加锁,可以适应不同的使用环境,代码如下:
void clear(bool is_lock = true)
{
if (is_lock)
{
boost::mutex::scoped_lock lock(m_mutex);
std::list<T>::clear();
}else
{
std::list<T>::clear();
}
}
3 最后记得在模板类的析构函数位置加上clear函数,保证退出时释放资源,全部代码如下:
// locklist.h file here
#ifndef __locklist_h__
#define __locklist_h__
//
#include "list"
#include "stldef.h"
#include <algorithm>
#include <boost/thread.hpp>
template<typename T>
class CLockList
: public std::list<T>
{
protected:
boost::mutex m_mutex;
public:
boost::mutex & mutex(void) {return m_mutex;}
const boost::mutex & mutex(void) const {return m_mutex;}
void add(T t)
{
boost::mutex::scoped_lock lock(m_mutex);
std::list<T>::push_back(t);
}
bool front(T & out, bool is_pop = true)
{
boost::mutex::scoped_lock lock(m_mutex);
typename std::list<T>::iterator pIter = std::list<T>::begin();
if (pIter == std::list<T>::end())
return false;
out = *pIter;
if (is_pop)
std::list<T>::pop_front();
return true;
}
void clear(bool is_lock = true)
{
if (is_lock)
{
boost::mutex::scoped_lock lock(m_mutex);
std::list<T>::clear();
}else
{
std::list<T>::clear();
}
}
public:
CLockList(void)
{
}
~CLockList(void)
{
clear();
}
};
#endif // __locklist_h__
4 简单使用例子,假设有一个用户信息类CUserInfo,基本使用例子如下:
int main(void)
{
// 定义用户列表
CLockList<CUserInfo> m_users;
// 用户信息实例
CUserInfo user1;
CUserInfo user2;
// 添加
m_users.add(user1);
m_users.add(user2);
// 循环取出
CUserInfo userInfo;
while (m_users.front(userInfo))
{
// ...
}
// 在某些场合需要提前清空列表;
m_users.clear();
return 0;
}