• POCO C++库学习和分析——任务


    1、任务的定义

      任务虽然在Poco::Foundation库的目录中被单独划出来,其实可以被看成线程的应用,放在线程章节。首先来看一下Poco中对任务的描述:

      *task主要应用在GUI和Sever程序中,用于追踪后台线程的进度。

      *应用Poco任务时,需要类Poco::Task和类Poco::TaskManager配合使用。其中类Poco::Task继承自Poco::Runnable,它提供了接口可以便利的报告线程进度。Poco::TaskManager则对Poco::Task进行管理。

      *为了完成取消和上报线程进度的工作:

        a、使用者必须从Poco::Task创建一个子类并重写runTask()函数

        b、为了完成进度上报的功能,在子类的runTask()函数中,必须周期的调用setProgress()函数去上报信息

        c、为了能够在任务运行时终止任务,必须在子类的runTask()函数中,周期性地调用isCancelled()或者sleep()函数,去检查是否有任务停止请求

        d、如果isCancelled()或者sleep()返回真,runTask()返回。

      *Poco::TaskManager通过使用Poco::NotificationCenter去通知所有需要接受任务消息的对象

      从上面的描述可以看出,Poco中Task的功能就是能够自动汇报线程的运行进度。

    2、任务用例

      

     1 #include <iostream>
     2 #include "Poco/Task.h"
     3 #include "Poco/TaskManager.h"
     4 #include "Poco/TaskNotification.h"
     5 #include "Poco/Observer.h"
     6 #include <string>
     7 
     8 class TaskExample:public Poco::Task{
     9 public:
    10     TaskExample(const std::string name):Poco::Task(name){}
    11     void runTask(){
    12 
    13         for (int i = 0; i <= 100; i ++) {
    14             setProgress(float(i)/100);
    15             if (sleep(100)) {
    16                 break;
    17             }
    18         }
    19     }
    20 };
    21 class ProgressHandler{
    22 public:
    23     void onProgress(Poco::TaskProgressNotification * pNf){
    24         std::cout << pNf->task()->name() << " progress:";
    25         std::cout << pNf->progress()*100 << "%" << std::endl;
    26         pNf->release();
    27     }
    28     void onFinished(Poco::TaskFinishedNotification * pNf){
    29         std::cout << pNf->task()->name() << " finished.
    ";
    30         pNf->release();
    31     }
    32 };
    33 int main(int argc, char** argv)
    34 {
    35     Poco::TaskManager tm;
    36     ProgressHandler pm;
    37     tm.addObserver(Poco::Observer<ProgressHandler, Poco::TaskProgressNotification>
    38                    (pm,&ProgressHandler::onProgress)
    39                    );
    40     tm.addObserver(Poco::Observer<ProgressHandler, Poco::TaskFinishedNotification>
    41                    (pm,&ProgressHandler::onFinished)
    42                    );
    43     tm.start(new TaskExample("Task1"));
    44     tm.start(new TaskExample("Task2"));
    45     tm.joinAll();
    46     return 0;
    47 }

    (版权所有,本文转载自:http://blog.csdn.net/arau_sh/article/details/8620810

  • 相关阅读:
    谷粒商城网关服务建立(七)
    谷粒商城Nacos配置(六)
    谷粒商城Nacos配置(五)
    Nacos入门
    谷粒商城心得二
    谷粒商城的快速开发(四)
    谷粒商城的快速开发(三)
    谷粒商城心得一
    谷粒商城的环境搭建(二)
    PowerDesigner16安装&破解
  • 原文地址:https://www.cnblogs.com/mupiaomiao/p/4721537.html
Copyright © 2020-2023  润新知