| 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 | #ifndef BASE_TASK_H_INCLUDED | 
|---|
| 8 | #define BASE_TASK_H_INCLUDED | 
|---|
| 9 | #pragma once | 
|---|
| 10 |  | 
|---|
| 11 | #include "base/debug.h" | 
|---|
| 12 | #include "base/thread_pool.h" | 
|---|
| 13 |  | 
|---|
| 14 | #include <atomic> | 
|---|
| 15 | #include <functional> | 
|---|
| 16 |  | 
|---|
| 17 | namespace base { | 
|---|
| 18 |  | 
|---|
| 19 | class thread_pool; | 
|---|
| 20 |  | 
|---|
| 21 | class task_token { | 
|---|
| 22 | public: | 
|---|
| 23 | task_token() | 
|---|
| 24 | : m_canceled(false) | 
|---|
| 25 | , m_progress(0.0f) | 
|---|
| 26 | , m_progress_min(0.0f) | 
|---|
| 27 | , m_progress_max(1.0f) { } | 
|---|
| 28 |  | 
|---|
| 29 | bool canceled() const { return m_canceled; } | 
|---|
| 30 | float progress() const { return m_progress; } | 
|---|
| 31 |  | 
|---|
| 32 | void cancel() { m_canceled = true; } | 
|---|
| 33 | void set_progress(float p) { | 
|---|
| 34 | ASSERT(p >= 0.0f && p <= 1.0f); | 
|---|
| 35 | m_progress = m_progress_min | 
|---|
| 36 | + p * (m_progress_max - m_progress_min); | 
|---|
| 37 | } | 
|---|
| 38 | void set_progress_range(float min, float max) { | 
|---|
| 39 | m_progress_min = min; | 
|---|
| 40 | m_progress_max = max; | 
|---|
| 41 | } | 
|---|
| 42 |  | 
|---|
| 43 | private: | 
|---|
| 44 | std::atomic<bool> m_canceled; | 
|---|
| 45 | std::atomic<float> m_progress; | 
|---|
| 46 | float m_progress_min, m_progress_max; | 
|---|
| 47 | }; | 
|---|
| 48 |  | 
|---|
| 49 | class task { | 
|---|
| 50 | public: | 
|---|
| 51 | typedef std::function<void(task_token&)> func_t; | 
|---|
| 52 |  | 
|---|
| 53 | task(); | 
|---|
| 54 | ~task(); | 
|---|
| 55 |  | 
|---|
| 56 | void on_execute(func_t&& f) { m_execute = std::move(f); } | 
|---|
| 57 |  | 
|---|
| 58 | task_token& start(thread_pool& pool); | 
|---|
| 59 |  | 
|---|
| 60 | bool running() const { return m_running; } | 
|---|
| 61 |  | 
|---|
| 62 | // Returns true when the task is completed (whether it was | 
|---|
| 63 | // canceled or not). If this is true, it's safe to delete the task | 
|---|
| 64 | // instance (it will not be used anymore by any othe background | 
|---|
| 65 | // thread). | 
|---|
| 66 | bool completed() const { return m_completed; } | 
|---|
| 67 |  | 
|---|
| 68 | private: | 
|---|
| 69 | void in_worker_thread(); | 
|---|
| 70 |  | 
|---|
| 71 | std::atomic<bool> m_running; | 
|---|
| 72 | std::atomic<bool> m_completed; | 
|---|
| 73 | task_token m_token; | 
|---|
| 74 | func_t m_execute; | 
|---|
| 75 | }; | 
|---|
| 76 |  | 
|---|
| 77 | } // namespace base | 
|---|
| 78 |  | 
|---|
| 79 | #endif | 
|---|
| 80 |  | 
|---|