/* * Copyright 2014 Daniel Vrátil * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License or (at your option) version 3 or any later version * accepted by the membership of KDE e.V. (or its successor approved * by the membership of KDE e.V.), which shall act as a proxy * defined in Section 14 of version 3 of the license. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #ifndef ASYNC_H #define ASYNC_H #include #include #include #include #include #include "future.h" #include "async_impl.h" namespace Async { class JobBase; template class Job; template Job start(F func); namespace Private { template Async::Future* doExec(Job *job, const In & ... args); } class JobBase { template friend class Job; protected: enum JobType { Then, Each }; public: JobBase(JobType jobType, JobBase *prev = nullptr); virtual void exec() = 0; protected: JobBase *mPrev; void *mResult; JobType mJobType; }; template class Job : public JobBase { template friend class Job; template friend Job start(F_ func); typedef Out OutType; typedef typename std::tuple_element<0, std::tuple>::type InType; public: ~Job() { delete reinterpret_cast*>(mResult); } template Job then(F func) { return Job::create(func, JobBase::Then, this); } template Job each(F func) { return Job::create(func, JobBase::Each, this); } Async::Future result() const { return *reinterpret_cast*>(mResult); } void exec(); private: Job(JobBase::JobType jobType, JobBase *parent = nullptr) : JobBase(jobType, parent) { } template static Job create(F func, JobBase::JobType jobType, JobBase *parent = nullptr); public: std::function(In ...)> mFunc; }; } // namespace Async // ********** Out of line definitions **************** template Async::Job Async::start(F func) { return Job::create(func, JobBase::Then); } template Async::Future* Async::Private::doExec(Job *job, const In & ... args) { return new Async::Future(job->mFunc(args ...)); }; template void Async::Job::exec() { Async::Future *in = nullptr; if (mPrev) { mPrev->exec(); in = reinterpret_cast*>(mPrev->mResult); assert(in->isFinished()); } Job *job = dynamic_cast*>(this); Async::Future *out = Private::doExec(this, in ? in->value() : In() ...); out->waitForFinished(); job->mResult = reinterpret_cast(out); } template template Async::Job Async::Job::create(F func, Async::JobBase::JobType jobType, Async::JobBase* parent) { Job job(jobType, parent); job.mFunc = func; return job; } #endif // ASYNC_H