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 11 kB

6 years ago
6 years ago
6 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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 "minddata/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. master_->Interrupt();
  85. }
  86. Task *TaskManager::FindMe() {
  87. #if !defined(_WIN32) && !defined(_WIN64)
  88. return gMyTask;
  89. #else
  90. TaskManager &tm = TaskManager::GetInstance();
  91. SharedLock lock(&tm.lru_lock_);
  92. auto id = this_thread::get_id();
  93. auto tk = std::find_if(tm.lru_.begin(), tm.lru_.end(), [id](const Task &tk) { return tk.id_ == id; });
  94. if (tk != tm.lru_.end()) {
  95. return &(*tk);
  96. }
  97. // If we get here, either I am the watchdog or the master thread.
  98. if (tm.master_->id_ == id) {
  99. return tm.master_.get();
  100. } else if (tm.watchdog_ != nullptr && tm.watchdog_->id_ == id) {
  101. return tm.watchdog_;
  102. }
  103. MS_LOG(ERROR) << "Task not found.";
  104. return nullptr;
  105. #endif
  106. }
  107. TaskManager::TaskManager() try : global_interrupt_(0),
  108. lru_(&Task::node),
  109. free_lst_(&Task::free),
  110. watchdog_grp_(nullptr),
  111. watchdog_(nullptr) {
  112. auto alloc = Services::GetAllocator<Task>();
  113. // Create a dummy Task for the master thread (this thread)
  114. master_ = std::allocate_shared<Task>(alloc, "master", []() -> Status { return Status::OK(); });
  115. master_->id_ = this_thread::get_id();
  116. master_->running_ = true;
  117. master_->is_master_ = true;
  118. #if !defined(_WIN32) && !defined(_WIN64)
  119. gMyTask = master_.get();
  120. // Initialize the semaphore for the watchdog
  121. errno_t rc = sem_init(&sem_, 0, 0);
  122. if (rc == -1) {
  123. MS_LOG(ERROR) << "Unable to initialize a semaphore. Errno = " << rc << ".";
  124. std::terminate();
  125. }
  126. #endif
  127. } catch (const std::exception &e) {
  128. MS_LOG(ERROR) << "MindData initialization failed: " << e.what() << ".";
  129. std::terminate();
  130. }
  131. TaskManager::~TaskManager() {
  132. if (watchdog_) {
  133. WakeUpWatchDog();
  134. watchdog_->Join();
  135. // watchdog_grp_ and watchdog_ pointers come from Services::GetInstance().GetServiceMemPool() which we will free it
  136. // on shutdown. So no need to free these pointers one by one.
  137. watchdog_grp_ = nullptr;
  138. watchdog_ = nullptr;
  139. }
  140. #if !defined(_WIN32) && !defined(_WIN64)
  141. (void)sem_destroy(&sem_);
  142. #endif
  143. }
  144. Status TaskManager::DoServiceStart() {
  145. MS_LOG(INFO) << "Starting Task Manager.";
  146. #if !defined(_WIN32) && !defined(_WIN64)
  147. // Create a watchdog for control-c
  148. std::shared_ptr<MemoryPool> mp = Services::GetInstance().GetServiceMemPool();
  149. // A dummy group just for the watchdog. We aren't really using it. But most code assumes a thread must
  150. // belong to a group.
  151. auto f = std::bind(&TaskManager::WatchDog, this);
  152. Status rc;
  153. watchdog_grp_ = new (&rc, mp) TaskGroup();
  154. RETURN_IF_NOT_OK(rc);
  155. rc = watchdog_grp_->CreateAsyncTask("Watchdog", f, &watchdog_);
  156. if (rc.IsError()) {
  157. ::operator delete(watchdog_grp_, mp);
  158. watchdog_grp_ = nullptr;
  159. return rc;
  160. }
  161. grp_list_.erase(watchdog_grp_);
  162. lru_.Remove(watchdog_);
  163. #endif
  164. return Status::OK();
  165. }
  166. Status TaskManager::DoServiceStop() {
  167. WakeUpWatchDog();
  168. interrupt_all();
  169. return Status::OK();
  170. }
  171. Status TaskManager::WatchDog() {
  172. TaskManager::FindMe()->Post();
  173. #if !defined(_WIN32) && !defined(_WIN64)
  174. errno_t err = sem_wait(&sem_);
  175. if (err == -1) {
  176. RETURN_STATUS_UNEXPECTED("Errno = " + std::to_string(errno));
  177. }
  178. // We are woken up by control-c and we are going to stop all threads that are running.
  179. // In addition, we also want to prevent new thread from creating. This can be done
  180. // easily by calling the parent function.
  181. RETURN_IF_NOT_OK(ServiceStop());
  182. #endif
  183. return Status::OK();
  184. }
  185. // Follow the group link and interrupt other
  186. // Task in the same group. It is used by
  187. // Watchdog only.
  188. void TaskManager::InterruptGroup(Task &curTk) {
  189. TaskGroup *vg = curTk.MyTaskGroup();
  190. vg->interrupt_all();
  191. }
  192. void TaskManager::InterruptMaster(const Status &rc) {
  193. TaskManager &tm = TaskManager::GetInstance();
  194. std::shared_ptr<Task> master = tm.master_;
  195. std::lock_guard<std::mutex> lck(master->mux_);
  196. master->Interrupt();
  197. if (rc.IsError() && master->rc_.IsOk()) {
  198. master->rc_ = rc;
  199. master->caught_severe_exception_ = true;
  200. }
  201. }
  202. Status TaskManager::GetMasterThreadRc() {
  203. TaskManager &tm = TaskManager::GetInstance();
  204. std::shared_ptr<Task> master = tm.master_;
  205. Status rc = tm.master_->GetTaskErrorIfAny();
  206. if (rc.IsError()) {
  207. // Reset the state once we retrieve the value.
  208. std::lock_guard<std::mutex> lck(master->mux_);
  209. master->rc_ = Status::OK();
  210. master->caught_severe_exception_ = false;
  211. master->ResetIntrpState();
  212. }
  213. return rc;
  214. }
  215. void TaskManager::ReturnFreeTask(Task *p) noexcept {
  216. // Take it out from lru_ if any
  217. {
  218. UniqueLock lck(&lru_lock_);
  219. auto it = std::find(lru_.begin(), lru_.end(), *p);
  220. if (it != lru_.end()) {
  221. lru_.Remove(p);
  222. }
  223. }
  224. // We need to deallocate the string resources associated with the Task class
  225. // before we cache its memory for future use.
  226. p->~Task();
  227. // Put it back into free list
  228. {
  229. LockGuard lck(&free_lock_);
  230. free_lst_.Append(p);
  231. }
  232. }
  233. Status TaskManager::GetFreeTask(const std::string &my_name, const std::function<Status()> &f, Task **p) {
  234. if (p == nullptr) {
  235. RETURN_STATUS_UNEXPECTED("p is null");
  236. }
  237. Task *q = nullptr;
  238. // First try the free list
  239. {
  240. LockGuard lck(&free_lock_);
  241. if (free_lst_.count > 0) {
  242. q = free_lst_.head;
  243. free_lst_.Remove(q);
  244. }
  245. }
  246. if (q) {
  247. new (q) Task(my_name, f);
  248. } else {
  249. std::shared_ptr<MemoryPool> mp = Services::GetInstance().GetServiceMemPool();
  250. Status rc;
  251. q = new (&rc, mp) Task(my_name, f);
  252. RETURN_IF_NOT_OK(rc);
  253. }
  254. *p = q;
  255. return Status::OK();
  256. }
  257. Status TaskGroup::CreateAsyncTask(const std::string &my_name, const std::function<Status()> &f, Task **ppTask) {
  258. auto pMytask = TaskManager::FindMe();
  259. // We need to block ~TaskGroup coming otherwise we will deadlock. We will grab the
  260. // stateLock in shared allowing CreateAsyncTask to run concurrently.
  261. SharedLock state_lck(&state_lock_);
  262. // Now double check the state
  263. if (ServiceState() != STATE::kRunning) {
  264. return Status(StatusCode::kInterrupted, __LINE__, __FILE__, "Taskgroup is shutting down");
  265. }
  266. TaskManager &dm = TaskManager::GetInstance();
  267. Task *pTask = nullptr;
  268. // If the group is already in error, early exit too.
  269. // We can't hold the rc_mux_ throughout because the thread spawned by CreateAsyncTask may hit error which
  270. // will try to shutdown the group and grab the rc_mux_ and we will deadlock.
  271. {
  272. std::unique_lock<std::mutex> rcLock(rc_mux_);
  273. if (rc_.IsError()) {
  274. return pMytask->IsMasterThread() ? rc_ : Status(StatusCode::kInterrupted);
  275. }
  276. }
  277. RETURN_IF_NOT_OK(dm.CreateAsyncTask(my_name, f, this, &pTask));
  278. if (ppTask) {
  279. *ppTask = pTask;
  280. }
  281. return Status::OK();
  282. }
  283. void TaskGroup::interrupt_all() noexcept {
  284. // There is a racing condition if we don't stop the interrupt service at this point. New resource
  285. // may come in and not being picked up after we call InterruptAll(). So stop new comers and then
  286. // interrupt any existing resources.
  287. (void)intrp_svc_->ServiceStop();
  288. intrp_svc_->InterruptAll();
  289. }
  290. Status TaskGroup::join_all(Task::WaitFlag wf) {
  291. Status rc;
  292. Status rc2;
  293. SharedLock lck(&rw_lock_);
  294. for (Task &tk : grp_list_) {
  295. rc = tk.Join(wf);
  296. if (rc.IsError()) {
  297. rc2 = rc;
  298. }
  299. }
  300. return rc2;
  301. }
  302. Status TaskGroup::DoServiceStop() {
  303. interrupt_all();
  304. return (join_all(Task::WaitFlag::kNonBlocking));
  305. }
  306. TaskGroup::TaskGroup() : grp_list_(&Task::group), intrp_svc_(nullptr) {
  307. auto alloc = Services::GetAllocator<IntrpService>();
  308. intrp_svc_ = std::allocate_shared<IntrpService>(alloc);
  309. (void)Service::ServiceStart();
  310. }
  311. TaskGroup::~TaskGroup() {
  312. (void)Service::ServiceStop();
  313. // The TaskGroup is going out of scope, and we can return the Task list to the free list.
  314. Task *cur = grp_list_.head;
  315. TaskManager &tm = TaskManager::GetInstance();
  316. while (cur) {
  317. Task *next = cur->group.next;
  318. grp_list_.Remove(cur);
  319. tm.ReturnFreeTask(cur);
  320. cur = next;
  321. }
  322. {
  323. LockGuard lck(&tm.tg_lock_);
  324. (void)tm.grp_list_.erase(this);
  325. }
  326. }
  327. Status TaskGroup::GetTaskErrorIfAny() {
  328. SharedLock lck(&rw_lock_);
  329. for (Task &tk : grp_list_) {
  330. RETURN_IF_NOT_OK(tk.GetTaskErrorIfAny());
  331. }
  332. return Status::OK();
  333. }
  334. std::shared_ptr<IntrpService> TaskGroup::GetIntrpService() { return intrp_svc_; }
  335. } // namespace dataset
  336. } // namespace mindspore