任务虽然在Poco::Foundation库的目录结构中被单独划出,其实也可以被看成线程的应用,放在线程章节。首先来看一下Poco中对于任务的描述:
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; }
在类图中,我们可以看到Task类继承自RefCountedObject,这主要是为了Task类的管理。TaskManger对Task实现了自动的垃圾收集。
(版权所有,转载时请注明作者和出处 http://blog.csdn.net/arau_sh/article/details/8620810)