00001 /* 00002 * Copyright 2018 The Cartographer Authors 00003 * 00004 * Licensed under the Apache License, Version 2.0 (the "License"); 00005 * you may not use this file except in compliance with the License. 00006 * You may obtain a copy of the License at 00007 * 00008 * http://www.apache.org/licenses/LICENSE-2.0 00009 * 00010 * Unless required by applicable law or agreed to in writing, software 00011 * distributed under the License is distributed on an "AS IS" BASIS, 00012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 00013 * See the License for the specific language governing permissions and 00014 * limitations under the License. 00015 */ 00016 00017 #ifndef CARTOGRAPHER_COMMON_TASK_H_ 00018 #define CARTOGRAPHER_COMMON_TASK_H_ 00019 00020 #include <set> 00021 00022 #include "absl/synchronization/mutex.h" 00023 #include "glog/logging.h" 00024 #include "thread_pool.h" 00025 00026 namespace cartographer { 00027 namespace common { 00028 00029 class ThreadPoolInterface; 00030 00031 class Task { 00032 public: 00033 friend class ThreadPoolInterface; 00034 00035 using WorkItem = std::function<void()>; 00036 enum State { NEW, DISPATCHED, DEPENDENCIES_COMPLETED, RUNNING, COMPLETED }; 00037 00038 Task() = default; 00039 ~Task(); 00040 00041 State GetState() LOCKS_EXCLUDED(mutex_); 00042 00043 // State must be 'NEW'. 00044 void SetWorkItem(const WorkItem& work_item) LOCKS_EXCLUDED(mutex_); 00045 00046 // State must be 'NEW'. 'dependency' may be nullptr, in which case it is 00047 // assumed completed. 00048 void AddDependency(std::weak_ptr<Task> dependency) LOCKS_EXCLUDED(mutex_); 00049 00050 private: 00051 // Allowed in all states. 00052 void AddDependentTask(Task* dependent_task); 00053 00054 // State must be 'DEPENDENCIES_COMPLETED' and becomes 'COMPLETED'. 00055 void Execute() LOCKS_EXCLUDED(mutex_); 00056 00057 // State must be 'NEW' and becomes 'DISPATCHED' or 'DEPENDENCIES_COMPLETED'. 00058 void SetThreadPool(ThreadPoolInterface* thread_pool) LOCKS_EXCLUDED(mutex_); 00059 00060 // State must be 'NEW' or 'DISPATCHED'. If 'DISPATCHED', may become 00061 // 'DEPENDENCIES_COMPLETED'. 00062 void OnDependenyCompleted(); 00063 00064 WorkItem work_item_ GUARDED_BY(mutex_); 00065 ThreadPoolInterface* thread_pool_to_notify_ GUARDED_BY(mutex_) = nullptr; 00066 State state_ GUARDED_BY(mutex_) = NEW; 00067 unsigned int uncompleted_dependencies_ GUARDED_BY(mutex_) = 0; 00068 std::set<Task*> dependent_tasks_ GUARDED_BY(mutex_); 00069 00070 absl::Mutex mutex_; 00071 }; 00072 00073 } // namespace common 00074 } // namespace cartographer 00075 00076 #endif // CARTOGRAPHER_COMMON_TASK_H_