C++线程 -- boost::barrier解决多线程分工问题

来源:互联网 发布:物流网络存在的问题 编辑:程序博客网 时间:2024/06/05 17:33

问题描述:

在单线程逻辑中,在线程处理某个非常频繁事件时,而这个事件相对其他逻辑比较耗时。

这就像生产车间中,一个Main流水线在循环的执行流程工作,总是遇到一个非常频繁被执行且工作量大的流程挡着,为了来分担这个流程,那么我们开多个Work流水线去分担这个流程工作,且主流程去等待子流程的完成结果,再直接执行下面的流程。一旦Main流水线有单子下来分担给各个Work流水线去并行完成各个单子。Main线程就只负责拿到结果去完成下面的工作。

那么我们可以建立一个线程#include <boost/thread/barrier.hpp>曾用过boost::barrier这个类,非常简单的实现,简单说就是:计数等待barrier::barrier(unsigned int count)    : m_threshold(count), m_count(count), m_generation(0){    if (count == 0)        throw std::invalid_argument("count cannot be zero.");}看最重要的函数bool barrier::wait(){    boost::mutex::scoped_lock lock(m_mutex);    // m_mutex is the base of barrier and is initilized by it's default constructor.    unsigned int gen = m_generation;    // m_generation will be 0 for call 1~n-1, and 1 for n~2n - 1, and so on...    if (--m_count == 0)    {        m_generation++;    // cause m_generation to be changed in call n/2n/...        m_count = m_threshold;    // reset count        m_cond.notify_all();    // wake up all thread waiting here        return true;    }    while (gen == m_generation)    // if m_generation is not changed, lock current thread.        m_cond.wait(lock);    return false;}1、定义main thread:struct thread_cntl{std::atomic<int>  m_done_count; //线程计数器int work_threadnumb;  //线程数定义两个boost::barrier boost::barrier  bar_main(2) ; //为了等待main线程和其他工作线程,全部调用这激活boost::barrier  bar_work(work_threadnumb + 1); //所有Work线程等待和Main线程都调用后,激活};thread_cntl th_cntl;2、执行流程【】Work Thread:(每个工作线程所执行的事)while(1){th_cntl.bar_work.wait(); //①所有线程就绪等待Main线程.wait激活,⑤继续下一次就绪//从自己的工作列表中获取工作事件执行do_work();th_cntl.m_done_count++; //本Work线程执行完将计数加1//所有线程都计数了,表示都完成了if(th_cntl.m_done_count ==th_cntl.work_threadnumb){//所有流水线全部完成了th_cntl.bar_work->wait();//④最后一个线程也完成了任务调用Wait激活Main线程} }【】Main Threadth_cntl.bar_main.wait(); //②激活,开始工作th_cntl.bar_work.wait();//③等待最后一个Work线程完成时调用.wait()

执行流程就上面的①->⑤,主线程显得很清闲,但是谁让这个Main线程是管理呢,不过它才是重责在肩啊,呵呵,貌似很合乎社会现状。


0 0