【boost】使用装饰者模式改造boost::thread_group

在项目中使用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, 0, 0, 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 = 50;
        thread_group m_thread_group;
        list<thread *> m_list_ex;
        mutable shared_mutex m_ex;
    };
}

 

 

 

 

posted on 2013-09-10 11:49  小水坝  阅读(1683)  评论(0编辑  收藏  举报

导航