POCO C++库学习和分析 -- 任务
2013-02-28 10:28
260 查看
POCO C++库学习和分析 -- 任务
1. 任务的定义
任务虽然在Poco::Foundation库的目录结构中被单独划出,其实也可以被看成线程的应用,放在线程章节。首先来看一下Poco中对于任务的描述:task主要应用在GUI和Seerver程序中,用于追踪后台线程的进度。
应用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. 任务用例
Task的应用非常简单,下面是其一个使用例子:#include "Poco/Task.h" #include "Poco/TaskManager.h" #include "Poco/TaskNotification.h" #include "Poco/Observer.h" using Poco::Observer; class SampleTask: public Poco::Task { public: SampleTask(const std::string& name): Task(name) {} void runTask() { for (int i = 0; i < 100; ++i) { setProgress(float(i)/100); // report progress if (sleep(1000)) break; } } }; class ProgressHandler { public: void onProgress(Poco::TaskProgressNotification* pNf) { std::cout << pNf->task()->name() << " progress: " << pNf->progress() << std::endl; pNf->release(); } void onFinished(Poco::TaskFinishedNotification* pNf) { std::cout << pNf->task()->name() << " finished." << std::endl; pNf->release(); } }; int main(int argc, char** argv) { Poco::TaskManager tm; ProgressHandler pm; tm.addObserver( Observer<ProgressHandler, Poco::TaskProgressNotification> (pm, &ProgressHandler::onProgress) ); tm.addObserver( Observer<ProgressHandler, Poco::TaskFinishedNotification> (pm, &ProgressHandler::onFinished) ); tm.start(new SampleTask("Task 1")); // tm takes ownership tm.start(new SampleTask("Task 2")); tm.joinAll(); return 0; }
3. Task类图
最后给出Poco中Task的类图。在类图中,我们可以看到Task类继承自RefCountedObject,这主要是为了Task类的管理。TaskManger对Task实现了自动的垃圾收集。
(版权所有,转载时请注明作者和出处 http://blog.csdn.net/arau_sh/article/details/8620810)
相关文章推荐
- POCO C++库学习和分析 -- 平台与环境
- UCOS_II学习笔记---任务管理之请求删除任务函数分析
- POCO C++库学习和分析 -- 内存管理 (一)
- UCOS_II学习笔记---任务管理之建立任务函数分析
- POCO C++库学习和分析——任务
- POCO C++库学习和分析 -- 日志 (一)
- POCO C++库学习和分析 -- 内存管理 (三)
- POCO C++库学习和分析 -- 日志 (一)
- POCO C++库学习和分析 -- 流 (一)
- POCO C++库学习和分析 -- 内存管理 (二)
- POCO C++库学习和分析 -- 异常、错误处理、调试
- POCO C++库学习和分析 -- 线程 (三)
- POCO C++库学习和分析 -- Cache
- POCO C++库学习和分析 -- 内存管理 (二)
- Hadoop-2.4.1学习之Map任务源代码分析(下)
- POCO C++库学习和分析 -- UUID
- POCO C++库学习和分析 -- 平台与环境
- Hadoop-2.4.1学习之Map任务源码分析(下)
- POCO C++库学习和分析 -- 线程 (二)
- POCO C++库学习和分析 -- 哈希