1// LAF Base Library
2// Copyright (C) 2019 Igara Studio S.A.
3//
4// This file is released under the terms of the MIT license.
5// Read LICENSE.txt for more information.
6
7#ifdef HAVE_CONFIG_H
8#include "config.h"
9#endif
10
11#include "base/task.h"
12
13#include "base/debug.h"
14#include "base/log.h"
15
16namespace base {
17
18task::task()
19 : m_running(false)
20 , m_completed(false)
21{
22}
23
24task::~task()
25{
26 // The task must not be running when we are destroying it.
27 ASSERT(!m_running);
28
29 // m_completed can be false in this case if the task was never
30 // started (i.e. the user never called task::start()).
31 //ASSERT(m_completed);
32}
33
34task_token& task::start(thread_pool& pool)
35{
36 m_running = true;
37 pool.execute([this]{ in_worker_thread(); });
38 return m_token;
39}
40
41void task::in_worker_thread()
42{
43 try {
44 if (!m_token.canceled())
45 m_execute(m_token);
46 }
47 catch (const std::exception& ex) {
48 LOG(FATAL, "Exception running task: %s\n", ex.what());
49 }
50
51 m_running = false;
52
53 // This must be the latest statement in the worker thread (see
54 // task::complete() comment)
55 m_completed = true;
56}
57
58} // namespace base
59