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

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