利用ace的ACE_Task等类实现线程池

基于ACE的线程池学习与实现(一)——ACE_Task 这个主要是参考ACE官方文档写的 一、概述 ACE_Task 是ACE 中的任务或主动对象“处理结构”的基类。在ACE 中使用了此类来实现主动对象模式。所有希望成为“主动对象”的对象都必须从此类派生。你也可以把ACE_Task看作是更高级的、更为面向对象的线程类。 ACE_Task处理的是对象,因而在构造OO程序时更便于思考。因此,在大多数情况下,当你需要构建多线程程序时,较好的选择是使用A 阅读详情

本代码应该是ace自带的例子了,但是我觉得是非常好的,于是给大家分享一下。

注释非常详细啊。

头文件

#ifndef THREAD_POOL_H
#define THREAD_POOL_H

/* In order to implement a thread pool, we have to have an object that
   can create a thread.  The ACE_Task<> is the basis for doing just
   such a thing.  */
#include "ace/Task.h"

//add by ychen 20070714 below
#include "ace/Mutex.h"
//add by ychen 20070714 above

#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */

/* We need a forward reference for ACE_Event_Handler so that our
   enqueue() method can accept a pointer to one.  */
   
class ACE_Event_Handler;

/* Although we modified the rest of our program to make use of the
   thread pool implementation, if you look closely you'll see that the
   changes were rather minor.  The "ACE way" is generally to create a
   helper object that abstracts away the details not relevant to your
   application.  That's what I'm trying to do here by creating the
   Thread_Pool object.  */
class Thread_Pool : public ACE_Task<ACE_MT_SYNCH>
{
public:
  typedef ACE_Task<ACE_MT_SYNCH> inherited;

  /* Provide an enumeration for the default pool size.  By doing this,
    other objects can use the value when they want a default.  */
  enum size_t
  {
    default_pool_size_ = 1
  };

  // Basic constructor
  Thread_Pool (void);

  /* Opening the thread pool causes one or more threads to be
    activated.  When activated, they all execute the svc() method
    declared below.  */
  int open (int pool_size = default_pool_size_);

  /* Some compilers will complain that our open() above attempts to
    override a virtual function in the baseclass.  We have no
    intention of overriding that method but in order to keep the
    compiler quiet we have to add this method as a pass-thru to the
    baseclass method.  */
  virtual int open (void *void_data)
  {
    return inherited::open (void_data);
  }

  /*
   */
  virtual int close (u_long flags = 0);

  /* To use the thread pool, you have to put some unit of work into
    it.  Since we're dealing with event handlers (or at least their
    derivatives), I've chosen to provide an enqueue() method that
    takes a pointer to an ACE_Event_Handler.  The handler's
    handle_input() method will be called, so your object has to know
    when it is being called by the thread pool.  */
  int enqueue (ACE_Event_Handler *handler);

  /* Another handy ACE template is ACE_Atomic_Op<>.  When
    parameterized, this allows is to have a thread-safe counting
    object.  The typical arithmetic operators are all internally
    thread-safe so that you can share it across threads without
    worrying about any contention issues.  */
    typedef ACE_Atomic_Op<ACE_Mutex, int> counter_t;
  
protected:

  /* Our svc() method will dequeue the enqueued event handler objects
    and invoke the handle_input() method on each.  Since we're likely
    running in more than one thread, idle threads can take work from
    the queue while other threads are busy executing handle_input() on
    some object.  */
  int svc (void);

  /* We use the atomic op to keep a count of the number of threads in
    which our svc() method is running.  This is particularly important
    when we want to close() it down!  */
  counter_t active_threads_;
};

#endif /* THREAD_POOL_H */

实现文件

// thread_pool.cpp,v 1.9 1999/09/22 03:13:42 jcej Exp

#include "thread_pool.h"

/* We need this header so that we can invoke handle_input() on the
   objects we dequeue.  */
#include "ace/Event_Handler.h"

/* All we do here is initialize our active thread counter.  */
Thread_Pool::Thread_Pool (void)
  : active_threads_ (0)
{
}

/* Our open() method is a thin disguise around the ACE_Task<>
   activate() method.  By hiding activate() in this way, the users of
   Thread_Pool don't have to worry about the thread configuration
   flags.  */
int
Thread_Pool::open (int pool_size)
{
  return this->activate (THR_NEW_LWP|THR_DETACHED, pool_size);
}

/* Closing the thread pool can be a tricky exercise.  I've decided to
   take an easy approach and simply enqueue a secret message for each
   thread we have active.  */
int
Thread_Pool::close (u_long flags)
{
  ACE_UNUSED_ARG(flags);

  /* Find out how many threads are currently active */
  int counter = active_threads_.value ();

  /* For each one of the active threads, enqueue a "null" event
    handler.  Below, we'll teach our svc() method that "null" means
    "shutdown".  */
  while (counter--)
    this->enqueue (0);

  /* As each svc() method exits, it will decrement the active thread
    counter.  We just wait here for it to reach zero.  Since we don't
    know how long it will take, we sleep for a quarter of a second
    between tries.  */
  while (active_threads_.value ())
    ACE_OS::sleep (ACE_Time_Value (0, 250000));

  return(0);
}

/* When an object wants to do work in the pool, it should call the
   enqueue() method.  We introduce the ACE_Message_Block here but,
   unfortunately, we seriously misuse it.  */
int
Thread_Pool::enqueue (ACE_Event_Handler *handler)
{
  /* An ACE_Message_Block is a chunk of data.  You put them into an
    ACE_Message_Queue.  ACE_Task<> has an ACE_Message_Queue built in.
    In fact, the parameter to ACE_Task<> is passed directly to
    ACE_Message_Queue.  If you look back at our header file you'll see
    that we used ACE_MT_SYNCH as the parameter indicating that we want
    MultiThread Synch safety.  This allows us to safely put
    ACE_Message_Block objects into the message queue in one thread and
    take them out in another.  */

  /* An ACE_Message_Block wants to have char* data.  We don't have
    that.  We could cast our ACE_Event_Handler* directly to a char*
    but I wanted to be more explicit.  Since casting pointers around
    is a dangerous thing, I've gone out of my way here to be very
    clear about what we're doing.

    First: Cast the handler pointer to a void pointer.  You can't do
    any useful work on a void pointer, so this is a clear message that
    we're making the pointer unusable.

    Next: Cast the void pointer to a char pointer that the ACE_Message_Block will accept.  */
  void *v_data = (void *) handler;
  char *c_data = (char *) v_data;

  ACE_Message_Block *mb;

  /* Construct a new ACE_Message_Block.  For efficiency, you might
    want to preallocate a stack of these and reuse them.  For
    simplicity, I'll just create what I need as I need it.  */
  ACE_NEW_RETURN (mb,
                  ACE_Message_Block (c_data),
                  -1);

  /* Our putq() method is a wrapper around one of the enqueue methods
    of the ACE_Message_Queue that we own.  Like all good methods, it
    returns -1 if it fails for some reason.  */
  if (this->putq (mb) == -1)
    {
      /* Another trait of the ACE_Message_Block objects is that they
        are reference counted.  Since they're designed to be passed
        around between various objects in several threads we can't
        just delete them whenever we feel like it.  The release()
        method is similar to the destroy() method we've used
        elsewhere.  It watches the reference count and will delete the
        object when possible.  */
      mb->release ();
      return -1;
    }

  return 0;
}

/* The "guard" concept is very powerful and used throughout
   multi-threaded applications.  A guard normally does some operation
   on an object at construction and the "opposite" operation at
   destruction.  For instance, when you guard a mutex (lock) object,
   the guard will acquire the lock on construction and release it on
   destruction.  In this way, your method can simply let the guard go
   out of scope and know that the lock is released.

   Guards aren't only useful for locks however.  In this application
   I've created two guard objects for quite a different purpose.  */

/* The Counter_Guard is constructed with a reference to the thread
   pool's active thread counter.  The guard increments the counter
   when it is created and decrements it at destruction.  By creating
   one of these in svc(), I know that the counter will be decremented
   no matter how or where svc() returns.  */
class Counter_Guard
{
public:
  Counter_Guard (Thread_Pool::counter_t &counter)
    : counter_ (counter)
  {
    ++counter_;
  }

  ~Counter_Guard (void)
  {
    --counter_;
  }

protected:
  Thread_Pool::counter_t &counter_;
};

/* My Message_Block_Guard is also a little non-traditional.  It
   doesn't do anything in the constructor but it's destructor ensures
   that the message block's release() method is called.  This is a
   cheap way to prevent a memory leak if I need an additional exit
   point in svc().  */
class Message_Block_Guard
{
public:
  Message_Block_Guard (ACE_Message_Block *&mb)
    : mb_ (mb)
  {
  }

  ~Message_Block_Guard (void)
  {
    mb_->release ();
  }

protected:
  ACE_Message_Block *&mb_;
};

/* Now we come to the svc() method.  As I said, this is being executed
   in each thread of the Thread_Pool.  Here, we pull messages off of
   our built-in ACE_Message_Queue and cause them to do work.  */
int
Thread_Pool::svc (void)
{
  /* The getq() method takes a reference to a pointer.  So... we need
    a pointer to give it a reference to.  */
  ACE_Message_Block *mb;

  /* Create the guard for our active thread counter object.  No matter
    where we choose to return() from svc(), we now know that the
    counter will be decremented.  */
  Counter_Guard counter_guard (active_threads_);

  /* Get messages from the queue until we have a failure.  There's no
    real good reason for failure so if it happens, we leave
    immediately.  */
  while (this->getq (mb) != -1)
    {
      /* A successful getq() will cause "mb" to point to a valid
        refernce-counted ACE_Message_Block.  We use our guard object
        here so that we're sure to call the release() method of that
        message block and reduce it's reference count.  Once the count
        reaches zero, it will be deleted.  */
      Message_Block_Guard message_block_guard (mb);

      /* As noted before, the ACE_Message_Block stores it's data as a
        char*.  We pull that out here and later turn it into an
        ACE_Event_Handler* */
      char *c_data = mb->base ();

      /* We've chosen to use a "null" value as an indication to leave.
        If the data we got from the queue is not null then we have
        some work to do.  */
      if (c_data)
        {
          /* Once again, we go to great lengths to emphasize the fact
            that we're casting pointers around in rather impolite
            ways.  We could have cast the char* directly to an
            ACE_Event_Handler* but then folks might think that's an OK
            thing to do.

            (Note: The correct way to use an ACE_Message_Block is to
            write data into it.  What I should have done was create a
            message block big enough to hold an event handler pointer
            and then written the pointer value into the block.  When
            we got here, I would have to read that data back into a
            pointer.  While politically correct, it is also a lot of
            work.  If you're careful you can get away with casting
            pointers around.)  */
          void *v_data = (void *) c_data;

          ACE_Event_Handler *handler = (ACE_Event_Handler *) v_data;

          /* Now that we finally have an event handler pointer, invoke
            it's handle_input() method.  Since we don't know it's
            handle, we just give it a default.  That's OK because we
            know that we're not using the handle in the method anyway.  */
          if (handler->handle_input (ACE_INVALID_HANDLE) == -1)
            {
              /* Tell the handler that it's time to go home.  The
                "normal" method for shutting down a handler whose
                handler failed is to invoke handle_close().  This will
                take care of cleaning it up for us.  Notice how we use
                the handler's get_handle() method to populate it's
                "handle" parameter.  Convenient isn't it?  */
              handler->handle_close (handler->get_handle (), 0);

              /* Also notice that we don't exit the svc() method here!
                The first time I did this, I was exiting.  After a few
                clients disconnect you have an empty thread pool.
                Hard to do any more work after that...  */
            }
        }
      else
        /* If we get here, we were given a message block with "null"
           data.  That is our signal to leave, so we return(0) to
           leave gracefully.  */
          return 0;		// Ok, shutdown request

      // message_block_guard goes out of scope here and releases the
      // message_block instance.
    }

  return 0;
}


其中,对其中类中的两个变量使用了管理的思想。Counter_Guard类和Message_Block_Guard 类分别对其进行了管理。

因为ACE_Task类是使用了ACE_message_block 进行对消息的封装。因此使用类,防止了内存的泄漏。

ACE_Event_Handler  是事件句柄,类似于操作符。当我们处理的时候,对其进行处理。

更多文章欢迎访问:http://blog.csdn.net/wallwind


基于ACE应用编程框架——线程池(1) 一、基本的实现模型:    线程池的实现模型主要有两种:    1、半同步/半异步模型    在这种模型中,一个侦听线程负责接受请求,并在某个队列中缓冲它们。另外一组工作者线程负责处理请求。因此接受请求的线程并不是处理请求的线程。    2、领导者/跟随者模型    在这种模型中,有一个线程是领导者,其余线程是线程中的跟随者。当请求到达时,领导者首先获取请求,并在跟随者中选取一个作为新的领导者,然 阅读详情

相关推荐

ACE并发编程示例及Task类的实现

ACE_Task类的使用实例,并发编程概念讲解

ACE_Task介绍

ACE_Task 是ACE 中的任务或主动对象“处理结构”的基类。在ACE 中使用了此类来实现主动对象模式。所有希望成为“主动对象”的对象都必须从此类派生。你也可以把ACE_Task看作是更高级的、更为面向对象的线程类。相当于我们具体业务是继承ACE_Task这个类进行实现的。ACE_Task处理的是对象,因而在构造OO程序时更便于思考。因此,在大多数情况下,当你需要构建多线程程序时,较好的选择是...

qq_18343569的博客 918

利用ace的ACE_Task等类实现线程池的方法详解

本篇文章是对利用ace的ACE_Task等类实现线程池的方法进行了详细的分析介绍,需要的朋友参考下

ACE_Task介绍(生产者/消费者)v3.0

1ACE_Task 概述 ACE_Task是ACE中的任务或主动对象“处理结构”的基类。ACE使用此类来实现主动对象模式。所有希望成为“主动对象”的对象都必须由此类派生。同时可将它看作是更高级的、更为面向对象的线程。 ACE_Task处理的是对象,因此更有利于构造OO程序,产生更好的OO软件,而且,它还包括了一种用于 与其他任务通信的易于使用的机制。 ACE_Task

C++ 爱好者 make_it_simple888 6799

山东大学FPGA课程实验一 加法器设计

电子设计自动化与FPGA设计,实验一 加法器设计

2503_91283667的博客 877

【python】epub的电子书繁体字与简体字转换

中文繁体与简体转换

xiexianyou666的博客 3094

ACE_Task介绍(生产者/消费者)

概述 ACE_Task是ACE中的任务或主动对象“处理结构”的基类。ACE使用此类来实现主动对象模式。所有希望成为“主动对象”的对象都必须由此类派生。同时可将它看作是更高级的、更为面向对象的线程。 ACE_Task处理的是对象,因此更有利于构造OO程序,产生更好的OO软件,而且,它还包括了一种用于与其他任务通信的易于使用的机制。 ACE_Task可用作: 更高级的线程(常称

波波诸葛伟 1072

自学PCB思路 | PCB设计零基础入门-小白适用(附详细入门经验分享)

本人大一在实践课上就听说PCB,被虎的一楞一楞的,不过现在回看,发现其实并没有相信的那么难!想着把自己这一路摸索的学习路线分享一下,当时我是一边摸索一边上手,一把鼻涕一把泪的过来的。如果你想搞硬件或者需要搞硬件,下面是我的入门学习过程,希望可以帮到你。目录前言选择一款设计软件好的入门课程掌握抄板元件采购焊板子烙铁头热风枪自己半设计明确设计需求全设计最后我并非什么大佬,也没法自己去教大家如何画板。

自动化小秋葵的博客 1万+

ACE之Task框架

其提供了并发处理事件的能力。

多看多听多总结 1225

基于UCD3138的数字控制硬开关全桥DC-DC电源设计实战解析

在开关电源设计中,数字控制技术正逐步取代传统模拟方案,以其卓越的灵活性、可编程性和强大的数据处理能力,成为应对复杂动态响应与智能化需求的关键。其核心原理在于通过高精度模数转换器(ADC)实时采样电压、电流信号,经由数字信号处理器(如ARM内核)运行PID等控制算法,动态调整数字脉宽调制(DPWM)输出,从而实现对功率级的精确控制。这种技术价值体现在能够轻松实现高级算法(如输入电压前馈、非线性补偿)、灵活配置保护参数,并通过PMBus等接口实现智能化监控与管理。其典型应用场景包括通信基站、服务器电源以及工业设

1318

【异常】Cursor编辑器 “Taking longer than expected...“ 报错全链路排查与解决方案

该提示并非传统的程序崩溃或语法报错,本质是Cursor编辑器的超时预警机制——当核心任务(云端AI推理请求、本地项目索引等)的执行耗时超出系统预设阈值时,触发的用户告知类提示,核心诱因是任务执行全链路出现阻塞或性能瓶颈。以下方案按排查优先级从高到低排序,覆盖从快速急救到根因根治的全流程,可按步骤逐步验证解决。针对大仓库、多依赖项目的索引超时问题,核心是通过规则过滤无效文件,从根源降低索引负载。

奶爸的编程之路,也就一周冷个三天 3140

ACE_Task 理解

ACE_Task 理解 Table of Contents 1 ACE_Task 究竟是什么 1.1 类继承关系1.2 结构 1.2.1 激活这个线程:  activate() ,1.2.2 结束这个线程:  wait() .1.2.3 运行这个线程:  svc() , 1.3 用处 1   ACE_Task 究竟是什么 1.1   类继承

cherish_2012的专栏 1406

【OpenCV C++】基本绘图操作

OpenCV C++基本绘图操作程序说明代码运行效果 程序说明 // 程序描述:OpenCV C++基本绘图操作 //参 考:毛星云《OpenCV3编程入门》 // 操作系统: Windows 10 64bit // 开发语言: C++ // IDE 版 本:Visual Studio 2019 // OpenCV版本:4.20 代码 main函数写法很简单,先创建空表Mat图像,然后点用函数绘制化学原子图,接着绘制组合图,最后显示图像。 //-------------------------

程序员,他们想的是什么?他们想的永远都是技术,他们崇尚的也永远都是技术。 767

利用ACE 自己实现的线程池

1: 线程池组件的配置文件:   [log] ;DEBUG = 0 ;INFO = 1 ;WARN = 2 ;FAULT = 3 level=0 ;SCREENOUT = 0 ;FILEOUT = 1 ;BOTH = 2 director = 2 ;TEST = 0 ;RUN = 1 mode = 0 ;ONE = 0x00 ;FO

点点滴滴 1550

双目相机标定理论与编程实现

双目相机标定是计算机视觉中的重要任务,通过确定双目相机的内参和外参,可以实现立体视觉的深度感知和三维重建。通过使用OpenCV库提供的函数,我们可以方便地进行双目相机的标定工作。双目相机标定是计算机视觉中的重要任务,用于确定双目相机的内参和外参,以实现立体视觉的深度感知和三维重建。通过上述代码,我们可以获得左右相机的内参矩阵、畸变系数、旋转矩阵和平移矩阵等参数,从而完成双目相机的标定过程。使用双目相机采集一系列左右相机的图像,确保标定板在不同位置和角度下都能被双目相机拍摄到。函数来检测标定板的角点。

ByteKnight的博客 327

国资e学快速学习实战教程

本文主要介绍了国资e学快速学习实战教程,希望能对同学们有所帮助。 文章目录 1. 前言 2. 实战教程

weixin_43178406的博客 11万+

ACE - ACE_Method_Request, ACE_Task, ACE_Task_Base

// class ACE_Task : public ACE_Task_Base  # This is an example on how to implement a ACE thread pool. #:cat t.C   #include "ace/Synch.h"#include "ace/Synch_T.h"#include "ace/Activation

程序员码工的专栏 2179

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

ACE框架:ACE_Task

ACE:一个开源的、面向对象的工具包和框架,旨在简化复杂网络应用和服务的开发。

倔强老吕的博客 889

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

C++实现的带最大最小线程数的线程池(基于ACE)

最近需要一个能根据请求数变化的线程池,JAVA有这样的东西,可是C++下好像一般只是固定大小的线程池。所以就基于ACE写了个,只做了初步测试。主要思想是:1. 重载ACE_Task,这相当于是个固定线程池,用一个信号量(ACE_Thread_Semaphore)来记数空闲线程数。2. 初始化时根据用户的输入,确定最少线程数minnum和最大线程数maxnum,当多个请求到来,并且无空闲

zhenjiangge的专栏 1623

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

ace 实现的线程池,可以用ACE_Task_Base,ACE_Task,ACE_Svc_Handler作为工作者

头文件  1#include ace/Thread_Mutex.h>  2#include ace/Guard_T.h>  3#include ace/Svc_Handler.h>  4#include ace/Condition_T.h>  5#include ace/Atomic_Op.h>  6  7#include queue>  8  9// ---------

zzhongcy的专栏 1901

基于ACE应用编程框架——线程池

一、基本的实现模型:    线程池的实现模型主要有两种:    1、半同步/半异步模型    在这种模型中,一个侦听线程负责接受请求,并在某个队列中缓冲它们。另外一组工作者线程负责处理请求。因此接受请求的线程并不是处理请求的线程。    2、领导者/跟随者模型    在这种模型中,有一个线程是领导者,其余线程是线程中的跟随者。当请求到达时,领导者首先获取请求,并在跟随者中选取一个作为新的领导者,然

lemonxuexue的专栏 800

ACE_Task 多线程控制的一些参数

使用ACE_Task_Base类来对线程进行管理:     我们可以把线程的各种属性标志作为参数传递给ACE_Task_Base::active()方法,这样就可以创建具有某种或某些特殊属性的线程了;这些属性定义了线程将怎样被创建、调度、销毁等等;     线程创建标志:     THR_CANCEL_DISABLE : 不允许这个线程被取消;     THR_CANCEL_ENABLE

wintree的专栏 3410

ACE-Task主动对象

ACE中有一个独特的对象叫做主动对象,在ACE的官方文档中描述为:ACE_Task是ACE中的任务或主动对象处理结构的基类,在ACE中使用此结构来实现主动对象模式,所有希望成为主动对象的对象都必须从此类派生。 主动对象可以理解为在类的内部实现了线程,我们需要做的就是为线程创建相应的环境,实现线程的操作,然后开启线程。 要创建主动对象必须继承ACE_Task类,并实现下列方法: 1、初始化和终

zhoutong12589的专栏 661

ACE的线程创建

activate();/*默认创建一个线程*/

EveryDayOneHour的博客 501

关于ACE_Task::last_thread()

关于ACE_Task::last_thread()在ACE应用中,我们经常用ACE_Task类实现多线程处理。由于ACE_Svc_Handler从ACE_Task派生,当你写的应用程序使用了Acceptor-Connector框架同时又直接使用ACE_Task,如线程池,这时你会使用到ACE_Task。因为许多ACE_Task对应是动态分配的,所以,必须在不再需要时把它们正确地释放掉,知道何时

TAO工作室Stone Jiang的专栏 3376
上一篇: ACE反应器(Reactor)模式
下一篇: 在ACE中使用epoll
ctreewang
博客等级 码龄16年 1608粉丝 276原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址