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.

thread_pool.cc 13 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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 "src/runtime/thread_pool.h"
  17. #include <algorithm>
  18. #include "common/mslog.h"
  19. namespace mindspore {
  20. namespace predict {
  21. static constexpr int kThreadPoolMaxThreads = 8;
  22. static const int kCoreNumThr = 4;
  23. static const int kMidCoreNum = 2;
  24. static const int kBigCoreNum = 2;
  25. bool LiteQueue::Enqueue(const ThreadPoolTask &task) {
  26. const int tailIndex = tail.load(std::memory_order_relaxed);
  27. // queue full
  28. auto next = (tailIndex + 1) % kSingleThreadMaxTask;
  29. if (next == head.load(std::memory_order_acquire)) {
  30. return false;
  31. }
  32. buffer[tailIndex] = task;
  33. tail.store(next, std::memory_order_release);
  34. taskSize.fetch_add(1);
  35. return true;
  36. }
  37. bool LiteQueue::Dequeue(ThreadPoolTask *out) {
  38. if (out == nullptr) {
  39. MS_LOGE("ThreadPoolTask is nullptr");
  40. return false;
  41. }
  42. if (taskSize.load() == 0) {
  43. return false;
  44. }
  45. // queue empty
  46. const int headIndex = head.load(std::memory_order_relaxed);
  47. if (headIndex == tail.load(std::memory_order_acquire)) {
  48. return false;
  49. }
  50. *out = buffer[headIndex];
  51. head.store((headIndex + 1) % kSingleThreadMaxTask, std::memory_order_release);
  52. return true;
  53. }
  54. bool LiteThreadBind::Bind(int numThreads, int mode) {
  55. InitSortedCpuId();
  56. if (numThreads > static_cast<int>(sortedCpuIds.size())) {
  57. MS_LOGE("thread num %d is larger than cores %lu in the system", numThreads, sortedCpuIds.size());
  58. return false;
  59. }
  60. threadNums = numThreads + 1;
  61. bindModel = static_cast<AffinityMode>(mode);
  62. if (bindModel == NO_BIND) {
  63. if (!BindAllThread(false)) {
  64. MS_LOGE("unbind %d threads failed", threadNums);
  65. return false;
  66. }
  67. MS_LOGD("unbind %d threads successful", threadNums);
  68. } else {
  69. if (!BindAllThread(true)) {
  70. MS_LOGE("bind %d threads failed", threadNums);
  71. return false;
  72. }
  73. MS_LOGD("bind %d threads successful", threadNums);
  74. }
  75. return true;
  76. }
  77. void LiteThreadBind::InitSortedCpuId() {
  78. int numCores = static_cast<int>(std::thread::hardware_concurrency());
  79. if (numCores < kCoreNumThr) {
  80. bigCore = 0;
  81. midCore = numCores;
  82. } else {
  83. bigCore = kBigCoreNum;
  84. midCore = kMidCoreNum;
  85. }
  86. if (numCores > kCoreNumThr) {
  87. numCores = bigCore + midCore;
  88. }
  89. sortedCpuIds.resize(numCores);
  90. sortedCpuIds.clear();
  91. for (int i = numCores - 1; i >= 0; --i) {
  92. sortedCpuIds.emplace_back(i);
  93. }
  94. }
  95. bool LiteThreadBind::BindAllThread(bool bindFlag) {
  96. if (threadNums <= 0) {
  97. MS_LOGE("no thread pool find, current threadNums %d", threadNums);
  98. return false;
  99. }
  100. if (!BindThreads(bindFlag)) {
  101. MS_LOGE("bind threads failed");
  102. return false;
  103. }
  104. return true;
  105. }
  106. bool LiteThreadBind::BindMasterThread(bool bindFlag, int mode) {
  107. std::vector<int> cpu;
  108. cpu.resize(sortedCpuIds.size());
  109. cpu.clear();
  110. if (bindFlag) {
  111. int cpuIndex = (mode == MID_CORE) ? (threadNums - 1) : 0;
  112. auto materCpuId = sortedCpuIds.at(cpuIndex);
  113. cpu.emplace_back(materCpuId);
  114. } else {
  115. // unbind master
  116. cpu.assign(sortedCpuIds.begin(), sortedCpuIds.end());
  117. }
  118. cpu_set_t cpuSet;
  119. CPU_ZERO(&cpuSet);
  120. for (auto coreId : cpu) {
  121. CPU_SET(coreId, &cpuSet);
  122. }
  123. if (!SetCPUBind(pthread_self(), cpuSet)) {
  124. MS_LOGE("do master bind failed. mode: %d", mode);
  125. return false;
  126. }
  127. return true;
  128. }
  129. bool LiteThreadBind::BindThreads(bool bindFlag) {
  130. if (bindFlag) {
  131. if (bindModel != NO_BIND) {
  132. size_t bindNums = std::min(sortedCpuIds.size(), threadIdList.size());
  133. size_t coreIndex;
  134. cpu_set_t cpuSet;
  135. for (size_t i = 0; i < bindNums; ++i) {
  136. if (bindModel == MID_CORE) {
  137. coreIndex = sortedCpuIds.size() - i - 1;
  138. } else {
  139. coreIndex = i;
  140. }
  141. CPU_ZERO(&cpuSet);
  142. CPU_SET(sortedCpuIds[coreIndex], &cpuSet);
  143. if (!threadIdList[i].second) {
  144. MS_LOGD("threadIdList[%lu]=%lu, sortedCpuIds[%lu]=%d", i, threadIdList[i].first, coreIndex,
  145. sortedCpuIds[coreIndex]);
  146. if (!SetCPUBind(threadIdList[i].first, cpuSet)) {
  147. MS_LOGE("do SetCPUBind failed");
  148. return false;
  149. }
  150. }
  151. threadIdList[i].second = true;
  152. }
  153. }
  154. } else {
  155. // unbind
  156. size_t bindNums = std::min(sortedCpuIds.size(), threadIdList.size());
  157. cpu_set_t cpuSet;
  158. CPU_ZERO(&cpuSet);
  159. for (auto coreId : sortedCpuIds) {
  160. CPU_SET(coreId, &cpuSet);
  161. }
  162. for (size_t i = 0; i < bindNums; ++i) {
  163. if (!SetCPUBind(threadIdList[i].first, cpuSet)) {
  164. MS_LOGE("do SetCPUBind failed");
  165. return false;
  166. }
  167. threadIdList[i].second = false;
  168. }
  169. }
  170. return true;
  171. }
  172. bool LiteThreadBind::SetCPUBind(pthread_t threadId, const cpu_set_t &cpuSet) {
  173. #if defined(__ANDROID__)
  174. #if __ANDROID_API__ >= 21
  175. int ret = sched_setaffinity(pthread_gettid_np(threadId), sizeof(cpu_set_t), &cpuSet);
  176. if (ret != 0) {
  177. MS_LOGE("bind thread %ld to cpu failed.ERROR %d", threadId, ret);
  178. }
  179. #endif
  180. #else
  181. int ret = pthread_setaffinity_np(threadId, sizeof(cpu_set_t), &cpuSet);
  182. if (ret != 0) {
  183. MS_LOGE("bind thread %ld to cpu failed.ERROR %d", threadId, ret);
  184. return false;
  185. }
  186. #endif
  187. return true;
  188. }
  189. LiteThreadPool::LiteThreadPool(int numThreads) {
  190. queueList.resize(kThreadPoolMaxThreads);
  191. queueList.clear();
  192. AddNewThread(numThreads);
  193. }
  194. void LiteThreadPool::AddNewThread(int newNums) {
  195. for (int i = curThreadNums, j = 0; j < newNums; ++j, ++i) {
  196. queueList.push_back(std::unique_ptr<LiteQueue>(new LiteQueue()));
  197. threadList.emplace_back([this, i]() {
  198. ThreadPoolTask task;
  199. while (!destroy) {
  200. while (running != 0) {
  201. MS_LOGD("i = %d, thread id = %lu, taskSize = %d", i, pthread_self(), queueList[i]->taskSize.load());
  202. while (queueList[i]->taskSize.load() > 0 && queueList[i]->Dequeue(&task)) {
  203. auto ret = task.first(task.second.taskId, task.second.tvmParam, task.second.cdata);
  204. if (ret != 0) {
  205. errorInfo.emplace_back(std::make_pair(task.second.taskId, std::make_pair(false, ret)));
  206. }
  207. queueList[i]->taskSize.fetch_sub(1);
  208. }
  209. std::this_thread::yield();
  210. }
  211. std::unique_lock<std::mutex> queueLock(tMutex);
  212. queueReady.wait(queueLock, [this] { return destroy || running != 0; });
  213. }
  214. });
  215. }
  216. MS_LOGI("%d new thread create", newNums);
  217. curThreadNums += newNums;
  218. }
  219. bool LiteThreadPool::DistributeTask(ThreadPoolTask task, int numTask) {
  220. // wake up
  221. errorInfo.clear();
  222. if (!AddRunReference()) {
  223. MS_LOGE("add reference failed");
  224. return false;
  225. }
  226. bool kSuccFlag;
  227. for (int i = 1; i < numTask; ++i) {
  228. task.second.taskId = i;
  229. do {
  230. kSuccFlag = false;
  231. for (auto &queue : queueList) {
  232. MS_ASSERT(queue != nullptr);
  233. if (queue->Enqueue(task)) {
  234. kSuccFlag = true;
  235. break;
  236. }
  237. }
  238. std::this_thread::yield();
  239. } while (!kSuccFlag);
  240. }
  241. MS_LOGI("add %d task successful", numTask);
  242. // master thread
  243. int ret = task.first(0, task.second.tvmParam, task.second.cdata);
  244. if (ret != 0) {
  245. errorInfo.emplace_back(std::make_pair(0, std::make_pair(false, ret)));
  246. }
  247. kSuccFlag = false;
  248. while (!kSuccFlag) {
  249. kSuccFlag = true;
  250. for (auto iter = queueList.begin(); iter != queueList.end(); ++iter) {
  251. if ((*iter)->taskSize.load() != 0) {
  252. kSuccFlag = false;
  253. break;
  254. }
  255. }
  256. std::this_thread::yield();
  257. }
  258. // hibernate
  259. if (!SubRunReference()) {
  260. MS_LOGE("sub reference failed");
  261. return false;
  262. }
  263. MS_LOGI("finish %d task successful", numTask);
  264. return CheckResult();
  265. }
  266. bool LiteThreadPool::AddRunReference() {
  267. running.fetch_add(1);
  268. std::lock_guard<std::mutex> queueLock(tMutex);
  269. queueReady.notify_all();
  270. return true;
  271. }
  272. bool LiteThreadPool::SubRunReference() {
  273. running.fetch_sub(1);
  274. return true;
  275. }
  276. bool LiteThreadPool::CheckResult() {
  277. bool kSuccFlag = true;
  278. for (auto result : errorInfo) {
  279. if (result.second.first) {
  280. MS_LOGE("task %d failed, error code is %d", result.first, result.second.second);
  281. kSuccFlag = false;
  282. }
  283. }
  284. return kSuccFlag;
  285. }
  286. int ThreadPool::GetThreadNum(int numThreads) {
  287. if (numThreads <= 0 || numThreads > kThreadPoolMaxThreads) {
  288. MS_LOGE("numThreads %d, must be greater than 0 or less than or equal to %d", numThreads, kThreadPoolMaxThreads);
  289. return -1;
  290. } else {
  291. if (numThreads > totalThreadNum) {
  292. return (numThreads - totalThreadNum);
  293. } else {
  294. MS_LOGD("%d threads have been already created", numThreads);
  295. return 0;
  296. }
  297. }
  298. }
  299. void ThreadPool::GetThreadIdList() {
  300. if (gThreadPool != nullptr) {
  301. for (int i = 0; i < totalThreadNum; ++i) {
  302. bool kSuccFlag = false;
  303. pthread_t threadHandle;
  304. do {
  305. kSuccFlag = false;
  306. threadHandle = gThreadPool->threadList[i].native_handle();
  307. if (threadHandle != 0) {
  308. kSuccFlag = true;
  309. }
  310. std::this_thread::yield();
  311. } while (!kSuccFlag);
  312. auto iter = std::find_if(std::begin(gThreadBind->threadIdList), std::end(gThreadBind->threadIdList),
  313. [threadHandle](std::pair<pthread_t, bool> id) { return id.first == threadHandle; });
  314. if (iter == std::end(gThreadBind->threadIdList)) {
  315. gThreadBind->threadIdList.emplace_back(std::make_pair(threadHandle, false));
  316. }
  317. }
  318. }
  319. MS_ASSERT(gThreadBind != nullptr);
  320. gThreadBind->threadIdList.emplace_back(std::make_pair(pthread_self(), false));
  321. }
  322. bool ThreadPool::SetThreadCpulBind(int mode) {
  323. if (totalThreadNum <= 0) {
  324. MS_LOGE("no threads need to be bind, totalThreadNum : %d", totalThreadNum);
  325. return false;
  326. }
  327. std::lock_guard<std::mutex> bMutex(gPoolMutex);
  328. if (gThreadBind == nullptr) {
  329. gThreadBind = std::unique_ptr<LiteThreadBind>(new (std::nothrow) LiteThreadBind());
  330. if (gThreadBind == nullptr) {
  331. MS_LOGE("new LiteThreadBind failed");
  332. return false;
  333. }
  334. gThreadBind->threadIdList.resize(kThreadPoolMaxThreads + 1);
  335. gThreadBind->threadIdList.clear();
  336. }
  337. GetThreadIdList();
  338. if (!gThreadBind->Bind(totalThreadNum, mode)) {
  339. MS_LOGE("BindCore failed");
  340. return false;
  341. }
  342. return true;
  343. }
  344. bool ThreadPool::SetThreadPool(int numThreads) {
  345. std::lock_guard<std::mutex> Lock(gPoolMutex);
  346. int realNums = GetThreadNum(numThreads);
  347. if (realNums < -1) {
  348. return false;
  349. }
  350. if (realNums == 0) {
  351. return true;
  352. }
  353. if (gThreadPool == nullptr) {
  354. gThreadPool = std::unique_ptr<LiteThreadPool>(new (std::nothrow) LiteThreadPool(realNums));
  355. if (gThreadPool == nullptr) {
  356. MS_LOGE("%d threads create failed", realNums);
  357. return false;
  358. }
  359. } else {
  360. gThreadPool->AddNewThread(realNums);
  361. }
  362. MS_LOGD("%d threads create successful", realNums);
  363. return true;
  364. }
  365. ThreadPool *ThreadPool::GetInstance() {
  366. static ThreadPool instance;
  367. return &instance;
  368. }
  369. void ThreadPool::ConfigThreadPool(int mode, int numThreads) {
  370. bindMode = mode;
  371. totalThreadNum = numThreads;
  372. }
  373. bool ThreadPool::LaunchThreadPoolTask() {
  374. if (gThreadPool == nullptr) {
  375. if (!SetThreadPool(totalThreadNum)) {
  376. MS_LOGE("create %d threads failed", totalThreadNum);
  377. return false;
  378. }
  379. }
  380. if (gThreadBind == nullptr) {
  381. if (!SetThreadCpulBind(bindMode)) {
  382. MS_LOGE("create bind mode %d failed", bindMode);
  383. return false;
  384. }
  385. }
  386. return true;
  387. }
  388. bool ThreadPool::AddTask(const WorkFun &worker, void *cdata, int numTask) {
  389. if (numTask <= 0) {
  390. numTask = totalThreadNum;
  391. }
  392. // single task, run master thread
  393. if (numTask <= 1) {
  394. TvmEnv env{};
  395. env.num_task = numTask;
  396. int ret = worker(0, &env, cdata);
  397. if (ret != 0) {
  398. MS_LOGE("task 0 failed, error code is %d", ret);
  399. return false;
  400. }
  401. MS_LOGD("task 0 successful");
  402. return true;
  403. }
  404. ThreadPoolTask task;
  405. task.first = worker;
  406. task.second.cdata = cdata;
  407. return gThreadPool->DistributeTask(task, numTask);
  408. }
  409. LiteThreadPool::~LiteThreadPool() {
  410. destroy.store(true);
  411. running.store(0);
  412. queueReady.notify_all();
  413. for (auto &thread : threadList) {
  414. if (thread.joinable()) {
  415. thread.join();
  416. }
  417. }
  418. }
  419. } // namespace predict
  420. } // namespace mindspore