Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <thread>
- #include <memory>
- #include <functional>
- #include <future>
- #include <vector>
- #include <deque>
- using namespace std;
- enum class ioctl_code
- {
- OK,
- FAILED
- };
- struct dev_io_cmd
- {
- ioctl_code code;
- };
- struct action_result
- {
- bool overall_result_;
- int system_error_;
- };
- class action_if
- {
- public:
- virtual action_result operator() () = 0;
- };
- class failed_action : public action_if
- {
- public:
- action_result operator() () override
- {
- action_result result_{ false, -1 };
- printf("failed action coming through\n");
- return result_;
- }
- };
- class successful_action : public action_if
- {
- public:
- action_result operator() () override
- {
- action_result result_{ true, 0 };
- printf("success is achieved\n");
- return result_;
- }
- };
- using action_vector = vector<unique_ptr<action_if>>;
- class actions_factory
- {
- public:
- action_vector create_actions(ioctl_code code)
- {
- action_vector vec;
- switch(code)
- {
- case ioctl_code::OK:
- vec.emplace_back( make_unique<successful_action>() );
- break;
- case ioctl_code::FAILED:
- vec.emplace_back( make_unique<failed_action>() );
- }
- return vec;
- }
- };
- class executor
- {
- public:
- action_result execute(action_vector& vec)
- {
- action_result result;
- for (auto &x : vec)
- {
- result = (*x)();
- if (!result.overall_result_)
- {
- break;
- }
- }
- return result;
- }
- };
- using action_task = packaged_task<action_result()>;
- using action_tasks = deque<action_task>;
- class dispatcher;
- extern dispatcher* global_disp;
- class dispatcher
- {
- public:
- dispatcher()
- : lock_{}
- , tasks_{}
- {
- }
- dispatcher(dispatcher&& disp)
- : lock_{ }
- , tasks_{ std::move(disp.tasks_) }
- {
- }
- void operator() ()
- {
- global_disp = this;
- cout << "im in" << endl;
- while (true)
- {
- lock_.lock();
- for (auto &x: tasks_)
- {
- lock_.unlock();
- x();
- lock_.lock();
- }
- tasks_.clear();
- lock_.unlock();
- }
- }
- void add_task(action_task&& task)
- {
- std::lock_guard<std::mutex> lock{lock_};
- tasks_.emplace_back(std::move(task));
- }
- private:
- mutex lock_;
- action_tasks tasks_;
- };
- dispatcher* global_disp;
- int main()
- {
- dispatcher disp;
- actions_factory factory;
- action_vector vec = factory.create_actions(ioctl_code::OK);
- executor exec;
- auto func = std::bind(executor::execute, exec, std::ref(vec));
- packaged_task<action_result()> task{ func };
- future<action_result> f = task.get_future();
- disp.add_task(std::move(task));
- std::thread thr{ std::move(disp) };
- f.wait();
- action_result result = f.get();
- cout << "overall result" << result.overall_result_ << endl;
- thr.join();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement