如果有人建议最终删除使用的上下文对象代表通过一系列步骤处理的作业,我会很感激。
在下面的代码中,创建了类text_file_processing_request
的对象并将其发送到io_service。我的管道由一步组成,实际代码中可能有更多步骤。
现在,我希望获得关于删除text_file_processing_request
类型对象的最佳方法的意见。
谢谢!
#include <iostream>
#include "boost/asio.hpp"
#include "boost/thread.hpp"
using namespace std;
namespace asio = boost::asio;
typedef std::unique_ptr<asio::io_service::work> work_ptr;
typedef boost::function<void(void) > parse_and_aggregate_fun_t;
class file_processing_request{
public:
virtual void process(int num) = 0;
};
class text_file_processing_request : public file_processing_request {
public:
virtual void process(int num) {
cout << "text_file_processing_request::process " << num << endl;
}
};
class processor {
public:
processor(int threads) : thread_count(threads) {
service = new asio::io_service();
work = new work_ptr(new asio::io_service::work(*(service)));
for (int i = 0; i < this->thread_count; ++i)
workers.create_thread(boost::bind(&asio::io_service::run, service));
}
void post_task(parse_and_aggregate_fun_t job){
this->service->post(job);
}
void stop(){
this->work->reset();
}
void wait(){
this->workers.join_all();
}
private:
int thread_count;
work_ptr * work;
asio::io_service* service;
boost::thread_group workers;
};
class job_discoverer {
public:
job_discoverer(processor *p): worker(p){}
void start_producing(){
do {
file_processing_request * cPtr = new text_file_processing_request();
this->worker->post_task(boost::bind(&file_processing_request::process, cPtr, 42));
} while (0);
this->worker->stop(); // no more data to process
}
private:
processor *worker;
};
int main(int argc, char** argv) {
processor *pr = new processor(4);
job_discoverer disocverer(pr);
disocverer.start_producing();
pr->wait();
delete pr;
return 0;
}