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