/* * 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 { template class Job; template Job start(const std::function(In ...)> &func); class JobBase { public: JobBase(JobBase *prev = nullptr) : mPrev(prev) , mResult(0) {} virtual void exec() = 0; public: JobBase *mPrev; void *mResult; }; namespace Private { template typename std::enable_if::value, void>::type doExec(JobBase *prev, JobBase *jobBase); template typename std::enable_if::type doExec(JobBase *prev, JobBase *jobBase, int * /* disambiguate */ = 0); } template class Job : public JobBase { template friend class Job; template friend Job start(F_ func); public: ~Job() { // Can't delete in JobBase, since we don't know the type // and deleting void* is undefined delete reinterpret_cast*>(mResult); } template Job then(F func) { Job job(this); job.mFunc = func; return job; } Async::Future result() const { return *reinterpret_cast*>(mResult); } void exec() { Async::Private::doExec(mPrev, this); } private: Job(JobBase *parent = nullptr) : JobBase(parent) {} public: std::function(In ...)> mFunc; }; template Job start(F func) { Job job; job.mFunc = std::function(In ...)>(func); return job; } } // namespace Async template typename std::enable_if::value, void>::type Async::Private::doExec(JobBase *prev, JobBase *jobBase) { prev->exec(); Async::Future *in = reinterpret_cast*>(prev->mResult); assert(in->isFinished()); Job *job = dynamic_cast*>(jobBase); Async::Future *out = new Async::Future(job->mFunc(in->value())); out->waitForFinished(); job->mResult = reinterpret_cast(out); }; template typename std::enable_if::type Async::Private::doExec(JobBase *prev, JobBase *jobBase, int * /* disambiguation */ = 0) { if (prev) { prev->exec(); Async::Future *in = reinterpret_cast*>(prev->mResult); assert(in->isFinished()); } Job *job = dynamic_cast*>(jobBase); Async::Future *out = new Async::Future(job->mFunc()); out->waitForFinished(); job->mResult = reinterpret_cast(out); }; #endif // ASYNC_H