POCO C++庫學習和分析 -- 通知和事件
阿新 • • 發佈:2019-01-10
#include <iostream>
#include "Poco/Task.h"
#include "Poco/TaskManager.h"
#include "Poco/TaskNotification.h"
#include "Poco/Observer.h"
using Poco::Observer;
using namespace std;
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實現了自動的垃圾收集。
#include "Poco/Task.h"
#include "Poco/TaskManager.h"
#include "Poco/TaskNotification.h"
#include "Poco/Observer.h"
using Poco::Observer;
using namespace std;
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實現了自動的垃圾收集。