您的位置:首页 > 其它

利用boost::mutex实现线程安全列表模板类,附源码及使用例子

2010-05-13 09:47 471 查看
std::list本身不具备线程安全功能,本文利用开源库boost的互斥体类mutex实现一个带互斥功能的线程安全列表模板类。
1 [/b]定义一个模板类,继承于[/b]std::list[/b],增加[/b]boost::mutex[/b]成员变量,代码如下:[/b][/b]
#include "list"
#include <boost/thread.hpp>
template<typename T>
class CLockList
: public std::list<T>
{
protected:
boost::mutex m_mutex;
};
2 [/b]我们主要实现[/b]add[/b]、[/b]front[/b]和[/b]clear[/b]三个函数,带互斥功能,其他功能函数可以自行添加;[/b][/b]
add[/b]函数实现把元素添加到列表末尾,代码如下:[/b]
void add(T t)
{
boost::mutex::scoped_lock lock(m_mutex);
std::list<T>::push_back(t);
}
front[/b]函数实现取出,列表头元素,is_pop[/b]决定是否删除该元素,代码如下:[/b]
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[/b]函数实现清空该列表,is_lock[/b]决定是否加锁,可以适应不同的使用环境,代码如下:[/b]
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();
}
}
[/b]3 [/b]最后记得在模板类的析构函数位置加上[/b]clear[/b]函数,保证退出时释放资源,全部代码如下:[/b][/b]
// 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 [/b]简单使用例子,假设有一个用户信息类[/b]CUserInfo[/b],基本使用例子如下:[/b][/b]
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐