Skip to content

Commit

Permalink
libcore: Improved async utility
Browse files Browse the repository at this point in the history
Added a method for terminating the thread (in exceptional
circumstances).
  • Loading branch information
skyjake committed Oct 12, 2017
1 parent 5caf24a commit b5254d9
Showing 1 changed file with 31 additions and 9 deletions.
40 changes: 31 additions & 9 deletions doomsday/sdk/libcore/include/de/core/async.h
Expand Up @@ -28,19 +28,20 @@

namespace de {

struct DENG2_PUBLIC AsyncTask : public QThread
{
virtual ~AsyncTask() {}
virtual void abort() = 0;
};

namespace internal {

template <typename Task, typename Completion>
struct AsyncTaskThread : public QThread
class AsyncTaskThread : public AsyncTask
{
Task task;
Completion completion;
decltype(task()) result {};

AsyncTaskThread(Task const &task, Completion const &completion)
: task(task)
, completion(completion)
{}
decltype(task()) result {}; // can't be void

void run() override
{
Expand All @@ -50,12 +51,29 @@ struct AsyncTaskThread : public QThread
}
catch (...)
{}
notifyCompletion();
}

void notifyCompletion()
{
Loop::mainCall([this] ()
{
completion(result);
deleteLater();
});
}

public:
AsyncTaskThread(Task const &task, Completion const &completion)
: task(task)
, completion(completion)
{}

void abort() override
{
terminate();
notifyCompletion();
}
};

} // namespace internal
Expand All @@ -72,14 +90,18 @@ struct AsyncTaskThread : public QThread
* a default-constructed result value.
* @param completion Completion callback. Takes one argument matching the type of
* the return value from @a task.
*
* @return Background thread object. The thread will delete itself after the completion
* callback has been called.
*/
template <typename Task, typename Completion>
void async(Task const &task, Completion const &completion)
AsyncTask *async(Task const &task, Completion const &completion)
{
DENG2_ASSERT_IN_MAIN_THREAD();
auto *t = new internal::AsyncTaskThread<Task, Completion>(task, completion);
t->start();
// The thread will delete itself when finished.
// Note: The thread will delete itself when finished.
return t;
}

} // namespace de
Expand Down

0 comments on commit b5254d9

Please sign in to comment.