【boost】使用装饰者模式改造boost::thread_group
2024-08-25 20:55:19
在项目中使用boost::thread_group的时候遇到几个问题:
1、thread_group不提供删除全部thread列表的方法,一直使用create会是其内部列表不断增加。
2、thread_group不提供try_join_for等方法,在线程中等待时,无法调用peekmessage函数来重新激活消息队列。
由于thread_group的接口本来就比较小,因此可以直接重写,但是这个时候使用装饰者模式无疑更加方便。
namespace boost
{
class thread_group_ex
{
private:
thread_group_ex(thread_group_ex const&);
thread_group_ex& operator=(thread_group_ex const&);
public:
thread_group_ex(){}
~thread_group_ex(){} bool is_this_thread_in()
{
return m_thread_group.is_this_thread_in();
} bool is_thread_in(thread* thrd)
{
return m_thread_group.is_thread_in(thrd);
} template<typename F>
thread* create_thread(F threadfunc)
{
thread* pthread = m_thread_group.create_thread(threadfunc);
m_list_ex.push_back(pthread);
return pthread;
} void add_thread(thread* thrd)
{
m_thread_group.add_thread(thrd);
if (thrd)
{
m_list_ex.push_back(thrd);
}
} void remove_thread(thread* thrd)
{
m_thread_group.remove_thread(thrd);
m_list_ex.remove(thrd);
} void join_all()
{
m_thread_group.join_all();
}
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
void interrupt_all()
{
m_thread_group.interrupt_all();
}
#endif
size_t size() const
{
return m_thread_group.size();
}
//try join all方法
//非阻塞等待所有线程返回
void try_join_all()
{
boost::shared_lock<shared_mutex> guard(m_ex); MSG msg; for (list<thread *>::iterator it=m_list_ex.begin(); it!=m_list_ex.end(); ++it)
{
if ((*it)->joinable())
{
while (!(*it)->try_join_for(chrono::milliseconds(wait_milliseconds)))
{
PeekMessage(&msg, NULL, , , PM_NOREMOVE);
}
}
}
}
//清空列表方法
void remove_all_thread()
{
boost::shared_lock<shared_mutex> guard(m_ex);
for (list<thread *>::iterator it=m_list_ex.begin(); it!=m_list_ex.end(); ++it)
{
m_thread_group.remove_thread(*it);
delete (*it);
}
m_list_ex.clear();
} private:
const static UINT wait_milliseconds = ;
thread_group m_thread_group;
list<thread *> m_list_ex;
mutable shared_mutex m_ex;
};
}
最新文章
- Css3:选择器、字体和颜色样式
- spring3.0注解
- PHP读文件的一个乱码问题
- onfiguration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]
- 【Linux】/dev/null 2>;&;1 详解
- Android手机_软件安装目录
- Form_Form Builder开发基于视图页面和自动代码生成包(案例)
- C#操作FTP, FTPHelper和SFTPHelper
- Python输出中文乱码问题
- (step8.2.6)hdu 1848(Fibonacci again and again——组合博弈)
- 在Windows下编译OpenSSL(VS2005和VC6)
- CTF大赛学习第一天!!!(学习中)
- java钉钉通讯录同步
- Eclipse的设置
- window.onunload中使用HTTP请求
- obj.attr = 5 == obj._dict_[";attr";] = 5,调用super相当于调用父类方法进行重新构造
- freeRTOS中文实用教程1--任务
- tomcat jetty
- mysql删除数据库文件ibdata1后引发的故障
- 【*】Redis实战场景中相关问题