You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

task_manager.cc 10 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. /**
  2. * Copyright 2019 Huawei Technologies Co., Ltd
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <algorithm>
  17. #include <functional>
  18. #include <set>
  19. #include "./securec.h"
  20. #include "dataset/util/task_manager.h"
  21. namespace mindspore {
  22. namespace dataset {
  23. // This takes the same parameter as Task constructor.
  24. Status TaskManager::CreateAsyncTask(const std::string &my_name, const std::function<Status()> &f, TaskGroup *vg,
  25. Task **task) {
  26. // We need to block destructor coming otherwise we will deadlock. We will grab the
  27. // stateLock in shared allowing CreateAsyncTask to run concurrently.
  28. SharedLock stateLck(&state_lock_);
  29. // Now double check the state
  30. if (ServiceState() == STATE::kStopInProg || ServiceState() == STATE::kStopped) {
  31. return Status(StatusCode::kInterrupted, __LINE__, __FILE__, "TaskManager is shutting down");
  32. }
  33. RETURN_IF_NOT_OK(GetFreeTask(my_name, f, task));
  34. if (vg == nullptr) {
  35. RETURN_STATUS_UNEXPECTED("TaskGroup is null");
  36. }
  37. // Previously there is a timing hole where the thread is spawn but hit error immediately before we can set
  38. // the TaskGroup pointer. We will do the set here before we call run(). The run() will do the registration.
  39. (*task)->set_task_group(vg);
  40. // Link to the master lru list.
  41. {
  42. UniqueLock lck(&lru_lock_);
  43. lru_.Append(*task);
  44. }
  45. // Link to the group list as well before we spawn.
  46. {
  47. UniqueLock lck(&vg->rw_lock_);
  48. vg->grp_list_.Append(*task);
  49. }
  50. // Track all the TaskGroup. Used for control-c
  51. {
  52. LockGuard lck(&tg_lock_);
  53. this->grp_list_.insert(vg);
  54. }
  55. RETURN_IF_NOT_OK((*task)->wp_.Register(vg));
  56. RETURN_IF_NOT_OK((*task)->Run());
  57. // Wait for the thread to initialize successfully.
  58. RETURN_IF_NOT_OK((*task)->Wait());
  59. return Status::OK();
  60. }
  61. Status TaskManager::join_all() {
  62. Status rc;
  63. Status rc2;
  64. SharedLock lck(&lru_lock_);
  65. for (Task &tk : lru_) {
  66. rc = tk.Join();
  67. if (rc.IsError()) {
  68. rc2 = rc;
  69. }
  70. }
  71. return rc2;
  72. }
  73. void TaskManager::interrupt_all() noexcept {
  74. global_interrupt_ = 1;
  75. LockGuard lck(&tg_lock_);
  76. for (TaskGroup *vg : grp_list_) {
  77. auto svc = vg->GetIntrpService();
  78. if (svc) {
  79. // Stop the interrupt service. No new request is accepted.
  80. svc->ServiceStop();
  81. svc->InterruptAll();
  82. }
  83. }
  84. (void)master_->Interrupt();
  85. }
  86. Task *TaskManager::FindMe() { return gMyTask; }
  87. TaskManager::TaskManager() try : global_interrupt_(0),
  88. lru_(&Task::node),
  89. free_lst_(&Task::free),
  90. watchdog_grp_(nullptr),
  91. watchdog_(nullptr) {
  92. std::shared_ptr<MemoryPool> mp = Services::GetInstance().GetServiceMemPool();
  93. Allocator<Task> alloc(mp);
  94. // Create a dummy Task for the master thread (this thread)
  95. master_ = std::allocate_shared<Task>(alloc, "master", []() -> Status { return Status::OK(); });
  96. master_->id_ = this_thread::get_id();
  97. master_->running_ = true;
  98. master_->is_master_ = true;
  99. gMyTask = master_.get();
  100. #if !defined(_WIN32) && !defined(_WIN64)
  101. // Initialize the semaphore for the watchdog
  102. errno_t rc = sem_init(&sem_, 0, 0);
  103. if (rc == -1) {
  104. MS_LOG(ERROR) << "Unable to initialize a semaphore. Errno = " << rc << ".";
  105. std::terminate();
  106. }
  107. #endif
  108. } catch (const std::exception &e) {
  109. MS_LOG(ERROR) << "MindData initialization failed: " << e.what() << ".";
  110. std::terminate();
  111. }
  112. TaskManager::~TaskManager() {
  113. if (watchdog_) {
  114. WakeUpWatchDog();
  115. watchdog_->Join();
  116. // watchdog_grp_ and watchdog_ pointers come from Services::GetInstance().GetServiceMemPool() which we will free it
  117. // on shutdown. So no need to free these pointers one by one.
  118. watchdog_grp_ = nullptr;
  119. watchdog_ = nullptr;
  120. }
  121. #if !defined(_WIN32) && !defined(_WIN64)
  122. (void)sem_destroy(&sem_);
  123. #endif
  124. }
  125. Status TaskManager::DoServiceStart() {
  126. MS_LOG(INFO) << "Starting Task Manager.";
  127. #if !defined(_WIN32) && !defined(_WIN64)
  128. // Create a watchdog for control-c
  129. std::shared_ptr<MemoryPool> mp = Services::GetInstance().GetServiceMemPool();
  130. // A dummy group just for the watchdog. We aren't really using it. But most code assumes a thread must
  131. // belong to a group.
  132. auto f = std::bind(&TaskManager::WatchDog, this);
  133. Status rc;
  134. watchdog_grp_ = new (&rc, mp) TaskGroup();
  135. RETURN_IF_NOT_OK(rc);
  136. rc = watchdog_grp_->CreateAsyncTask("Watchdog", f, &watchdog_);
  137. if (rc.IsError()) {
  138. ::operator delete(watchdog_grp_, mp);
  139. watchdog_grp_ = nullptr;
  140. return rc;
  141. }
  142. grp_list_.erase(watchdog_grp_);
  143. lru_.Remove(watchdog_);
  144. #endif
  145. return Status::OK();
  146. }
  147. Status TaskManager::DoServiceStop() {
  148. WakeUpWatchDog();
  149. interrupt_all();
  150. return Status::OK();
  151. }
  152. Status TaskManager::WatchDog() {
  153. TaskManager::FindMe()->Post();
  154. #if !defined(_WIN32) && !defined(_WIN64)
  155. errno_t err = sem_wait(&sem_);
  156. if (err == -1) {
  157. RETURN_STATUS_UNEXPECTED("Errno = " + std::to_string(errno));
  158. }
  159. // We are woken up by control-c and we are going to stop all threads that are running.
  160. // In addition, we also want to prevent new thread from creating. This can be done
  161. // easily by calling the parent function.
  162. RETURN_IF_NOT_OK(ServiceStop());
  163. #endif
  164. return Status::OK();
  165. }
  166. // Follow the group link and interrupt other
  167. // Task in the same group. It is used by
  168. // Watchdog only.
  169. void TaskManager::InterruptGroup(Task &curTk) {
  170. TaskGroup *vg = curTk.MyTaskGroup();
  171. vg->interrupt_all();
  172. }
  173. void TaskManager::InterruptMaster(const Status &rc) {
  174. TaskManager &tm = TaskManager::GetInstance();
  175. std::shared_ptr<Task> master = tm.master_;
  176. std::lock_guard<std::mutex> lck(master->mux_);
  177. (void)master->Interrupt();
  178. if (rc.IsError() && master->rc_.IsOk()) {
  179. master->rc_ = rc;
  180. master->caught_severe_exception_ = true;
  181. }
  182. }
  183. Status TaskManager::GetMasterThreadRc() {
  184. TaskManager &tm = TaskManager::GetInstance();
  185. std::shared_ptr<Task> master = tm.master_;
  186. Status rc = tm.master_->GetTaskErrorIfAny();
  187. if (rc.IsError()) {
  188. // Reset the state once we retrieve the value.
  189. std::lock_guard<std::mutex> lck(master->mux_);
  190. master->rc_ = Status::OK();
  191. master->caught_severe_exception_ = false;
  192. master->ResetIntrpState();
  193. }
  194. return rc;
  195. }
  196. void TaskManager::ReturnFreeTask(Task *p) noexcept {
  197. // Take it out from lru_ if any
  198. {
  199. UniqueLock lck(&lru_lock_);
  200. auto it = std::find(lru_.begin(), lru_.end(), *p);
  201. if (it != lru_.end()) {
  202. lru_.Remove(p);
  203. }
  204. }
  205. // We need to deallocate the string resources associated with the Task class
  206. // before we cache its memory for future use.
  207. p->~Task();
  208. // Put it back into free list
  209. {
  210. LockGuard lck(&free_lock_);
  211. free_lst_.Append(p);
  212. }
  213. }
  214. Status TaskManager::GetFreeTask(const std::string &my_name, const std::function<Status()> &f, Task **p) {
  215. if (p == nullptr) {
  216. RETURN_STATUS_UNEXPECTED("p is null");
  217. }
  218. Task *q = nullptr;
  219. // First try the free list
  220. {
  221. LockGuard lck(&free_lock_);
  222. if (free_lst_.count > 0) {
  223. q = free_lst_.head;
  224. free_lst_.Remove(q);
  225. }
  226. }
  227. if (q) {
  228. new (q) Task(my_name, f);
  229. } else {
  230. std::shared_ptr<MemoryPool> mp = Services::GetInstance().GetServiceMemPool();
  231. Status rc;
  232. q = new (&rc, mp) Task(my_name, f);
  233. RETURN_IF_NOT_OK(rc);
  234. }
  235. *p = q;
  236. return Status::OK();
  237. }
  238. Status TaskGroup::CreateAsyncTask(const std::string &my_name, const std::function<Status()> &f, Task **ppTask) {
  239. auto pMytask = TaskManager::FindMe();
  240. // We need to block ~TaskGroup coming otherwise we will deadlock. We will grab the
  241. // stateLock in shared allowing CreateAsyncTask to run concurrently.
  242. SharedLock state_lck(&state_lock_);
  243. // Now double check the state
  244. if (ServiceState() != STATE::kRunning) {
  245. return Status(StatusCode::kInterrupted, __LINE__, __FILE__, "Taskgroup is shutting down");
  246. }
  247. TaskManager &dm = TaskManager::GetInstance();
  248. Task *pTask = nullptr;
  249. // If the group is already in error, early exit too.
  250. // We can't hold the rc_mux_ throughout because the thread spawned by CreateAsyncTask may hit error which
  251. // will try to shutdown the group and grab the rc_mux_ and we will deadlock.
  252. {
  253. std::unique_lock<std::mutex> rcLock(rc_mux_);
  254. if (rc_.IsError()) {
  255. return pMytask->IsMasterThread() ? rc_ : Status(StatusCode::kInterrupted);
  256. }
  257. }
  258. RETURN_IF_NOT_OK(dm.CreateAsyncTask(my_name, f, this, &pTask));
  259. if (ppTask) {
  260. *ppTask = pTask;
  261. }
  262. return Status::OK();
  263. }
  264. void TaskGroup::interrupt_all() noexcept { (void)intrp_svc_->InterruptAll(); }
  265. Status TaskGroup::join_all() {
  266. Status rc;
  267. Status rc2;
  268. SharedLock lck(&rw_lock_);
  269. for (Task &tk : grp_list_) {
  270. rc = tk.Join();
  271. if (rc.IsError()) {
  272. rc2 = rc;
  273. }
  274. }
  275. return rc2;
  276. }
  277. Status TaskGroup::DoServiceStop() {
  278. intrp_svc_->ServiceStop();
  279. interrupt_all();
  280. return (join_all());
  281. }
  282. TaskGroup::TaskGroup() : grp_list_(&Task::group), intrp_svc_(nullptr) {
  283. std::shared_ptr<MemoryPool> mp = Services::GetInstance().GetServiceMemPool();
  284. Allocator<IntrpService> alloc(mp);
  285. intrp_svc_ = std::allocate_shared<IntrpService>(alloc);
  286. (void)Service::ServiceStart();
  287. }
  288. TaskGroup::~TaskGroup() {
  289. (void)Service::ServiceStop();
  290. // The TaskGroup is going out of scope, and we can return the Task list to the free list.
  291. Task *cur = grp_list_.head;
  292. TaskManager &tm = TaskManager::GetInstance();
  293. while (cur) {
  294. Task *next = cur->group.next;
  295. grp_list_.Remove(cur);
  296. tm.ReturnFreeTask(cur);
  297. cur = next;
  298. }
  299. {
  300. LockGuard lck(&tm.tg_lock_);
  301. (void)tm.grp_list_.erase(this);
  302. }
  303. }
  304. Status TaskGroup::GetTaskErrorIfAny() {
  305. SharedLock lck(&rw_lock_);
  306. for (Task &tk : grp_list_) {
  307. RETURN_IF_NOT_OK(tk.GetTaskErrorIfAny());
  308. }
  309. return Status::OK();
  310. }
  311. std::shared_ptr<IntrpService> TaskGroup::GetIntrpService() { return intrp_svc_; }
  312. } // namespace dataset
  313. } // namespace mindspore