2 * Copyright (c) 2023 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <dali/internal/system/common/async-task-manager-impl.h>
22 #include <dali/devel-api/adaptor-framework/environment-variable.h>
23 #include <dali/devel-api/adaptor-framework/thread-settings.h>
24 #include <dali/devel-api/common/singleton-service.h>
25 #include <dali/integration-api/adaptor-framework/adaptor.h>
26 #include <dali/integration-api/debug.h>
28 #include <unordered_map>
38 constexpr auto DEFAULT_NUMBER_OF_ASYNC_THREADS = size_t{8u};
39 constexpr auto NUMBER_OF_ASYNC_THREADS_ENV = "DALI_ASYNC_MANAGER_THREAD_POOL_SIZE";
41 // The number of threads for low priority task.
42 constexpr auto DEFAULT_NUMBER_OF_LOW_PRIORITY_THREADS = size_t{6u};
43 constexpr auto NUMBER_OF_LOW_PRIORITY_THREADS_ENV = "DALI_ASYNC_MANAGER_LOW_PRIORITY_THREAD_POOL_SIZE";
45 size_t GetNumberOfThreads(const char* environmentVariable, size_t defaultValue)
47 auto numberString = EnvironmentVariable::GetEnvironmentVariable(environmentVariable);
48 auto numberOfThreads = numberString ? std::strtoul(numberString, nullptr, 10) : 0;
49 constexpr auto MAX_NUMBER_OF_THREADS = 16u;
50 DALI_ASSERT_DEBUG(numberOfThreads <= MAX_NUMBER_OF_THREADS);
51 return (numberOfThreads > 0 && numberOfThreads <= MAX_NUMBER_OF_THREADS) ? numberOfThreads : defaultValue;
54 size_t GetNumberOfLowPriorityThreads(const char* environmentVariable, size_t defaultValue, size_t maxValue)
56 auto numberString = EnvironmentVariable::GetEnvironmentVariable(environmentVariable);
57 auto numberOfThreads = numberString ? std::strtoul(numberString, nullptr, 10) : 0;
58 DALI_ASSERT_DEBUG(numberOfThreads <= maxValue);
59 return (numberOfThreads > 0 && numberOfThreads <= maxValue) ? numberOfThreads : std::min(defaultValue, maxValue);
62 #if defined(DEBUG_ENABLED)
63 Debug::Filter* gAsyncTasksManagerLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_ASYNC_TASK_MANAGER");
65 uint32_t gThreadId = 0u; // Only for debug
68 } // unnamed namespace
72 AsyncTaskThread::AsyncTaskThread(AsyncTaskManager& asyncTaskManager)
74 mAsyncTaskManager(asyncTaskManager),
75 mLogFactory(Dali::Adaptor::Get().GetLogFactory()),
76 mTraceFactory(Dali::Adaptor::Get().GetTraceFactory()),
77 mDestroyThread(false),
78 mIsThreadStarted(false),
83 AsyncTaskThread::~AsyncTaskThread()
87 ConditionalWait::ScopedLock lock(mConditionalWait);
88 mDestroyThread = true;
89 mConditionalWait.Notify(lock);
95 bool AsyncTaskThread::Request()
100 mIsThreadStarted = true;
104 // Lock while adding task to the queue
105 ConditionalWait::ScopedLock lock(mConditionalWait);
109 mIsThreadIdle = false;
111 // wake up the thread
112 mConditionalWait.Notify(lock);
120 void AsyncTaskThread::Run()
122 #if defined(DEBUG_ENABLED)
123 uint32_t threadId = gThreadId++;
126 snprintf(temp, 100, "AsyncTaskThread[%u]", threadId);
130 SetThreadName("AsyncTaskThread");
132 mLogFactory.InstallLogFunction();
133 mTraceFactory.InstallTraceFunction();
135 while(!mDestroyThread)
137 AsyncTaskPtr task = mAsyncTaskManager.PopNextTaskToProcess();
140 ConditionalWait::ScopedLock lock(mConditionalWait);
143 mIsThreadIdle = true;
144 DALI_LOG_INFO(gAsyncTasksManagerLogFilter, Debug::General, "Thread[%u] wait\n", threadId);
145 mConditionalWait.Wait(lock);
146 DALI_LOG_INFO(gAsyncTasksManagerLogFilter, Debug::General, "Thread[%u] awake\n", threadId);
151 DALI_LOG_INFO(gAsyncTasksManagerLogFilter, Debug::General, "Thread[%u] Process task [%p]\n", threadId, task.Get());
153 DALI_LOG_INFO(gAsyncTasksManagerLogFilter, Debug::General, "Thread[%u] Complete task [%p]\n", threadId, task.Get());
156 mAsyncTaskManager.CompleteTask(std::move(task));
162 // AsyncTaskManager::CacheImpl
164 struct AsyncTaskManager::CacheImpl
166 CacheImpl(AsyncTaskManager& manager)
172 // Insert / Erase task cache API.
175 * @brief Insert cache that input task.
176 * @pre Mutex be locked.
178 template<typename CacheContainer, typename Iterator>
179 static void InsertTaskCache(CacheContainer& cacheMap, AsyncTaskPtr task, Iterator iterator)
181 auto& cacheContainer = cacheMap[task.Get()]; // Get or Create cache container.
182 cacheContainer.insert(cacheContainer.end(), iterator);
186 * @brief Erase cache that input task.
187 * @pre Mutex be locked.
189 template<typename CacheContainer, typename Iterator>
190 static void EraseTaskCache(CacheContainer& cacheMap, AsyncTaskPtr task, Iterator iterator)
192 auto mapIter = cacheMap.find(task.Get());
193 if(mapIter != cacheMap.end())
195 auto& cacheContainer = (*mapIter).second;
196 auto cacheIter = std::find(cacheContainer.begin(), cacheContainer.end(), iterator);
198 if(cacheIter != cacheContainer.end())
200 cacheContainer.erase(cacheIter);
201 if(cacheContainer.empty())
203 cacheMap.erase(mapIter);
210 * @brief Erase all cache that input task.
211 * @pre Mutex be locked.
213 template<typename CacheContainer>
214 static void EraseAllTaskCache(CacheContainer& cacheMap, AsyncTaskPtr task)
216 auto mapIter = cacheMap.find(task.Get());
217 if(mapIter != cacheMap.end())
219 cacheMap.erase(mapIter);
224 AsyncTaskManager& mManager; ///< Owner of this CacheImpl.
226 // Keep cache iterators as list since we take tasks by FIFO as default.
227 using TaskCacheContainer = std::unordered_map<const AsyncTask*, std::list<AsyncTaskContainer::iterator>>;
228 using RunningTaskCacheContainer = std::unordered_map<const AsyncTask*, std::list<AsyncRunningTaskContainer::iterator>>;
229 using CompletedTaskCacheContainer = std::unordered_map<const AsyncTask*, std::list<AsyncCompletedTaskContainer::iterator>>;
231 TaskCacheContainer mWaitingTasksCache; ///< The cache of tasks and iterator for waiting to async process. Must be locked under mWaitingTasksMutex.
232 RunningTaskCacheContainer mRunningTasksCache; ///< The cache of tasks and iterator for running tasks. Must be locked under mRunningTasksMutex.
233 CompletedTaskCacheContainer mCompletedTasksCache; ///< The cache of tasks and iterator for completed async process. Must be locked under mCompletedTasksMutex.
238 Dali::AsyncTaskManager AsyncTaskManager::Get()
240 Dali::AsyncTaskManager manager;
241 SingletonService singletonService(SingletonService::Get());
244 // Check whether the async task manager is already created
245 Dali::BaseHandle handle = singletonService.GetSingleton(typeid(Dali::AsyncTaskManager));
248 // If so, downcast the handle of singleton
249 manager = Dali::AsyncTaskManager(dynamic_cast<Internal::Adaptor::AsyncTaskManager*>(handle.GetObjectPtr()));
254 // If not, create the async task manager and register it as a singleton
255 Internal::Adaptor::AsyncTaskManager* internalAsyncTaskManager = new Internal::Adaptor::AsyncTaskManager();
256 manager = Dali::AsyncTaskManager(internalAsyncTaskManager);
257 singletonService.Register(typeid(manager), manager);
263 AsyncTaskManager::AsyncTaskManager()
264 : mTasks(GetNumberOfThreads(NUMBER_OF_ASYNC_THREADS_ENV, DEFAULT_NUMBER_OF_ASYNC_THREADS), [&]() { return TaskHelper(*this); }),
265 mAvaliableLowPriorityTaskCounts(GetNumberOfLowPriorityThreads(NUMBER_OF_LOW_PRIORITY_THREADS_ENV, DEFAULT_NUMBER_OF_LOW_PRIORITY_THREADS, mTasks.GetElementCount())),
266 mWaitingHighProirityTaskCounts(0u),
267 mCacheImpl(new CacheImpl(*this)),
268 mTrigger(new EventThreadCallback(MakeCallback(this, &AsyncTaskManager::TasksCompleted))),
269 mProcessorRegistered(false)
273 AsyncTaskManager::~AsyncTaskManager()
275 if(mProcessorRegistered && Dali::Adaptor::IsAvailable())
277 mProcessorRegistered = false;
278 Dali::Adaptor::Get().UnregisterProcessor(*this);
284 // Remove cache impl after all threads are join.
287 // Remove tasks after CacheImpl removed
288 mWaitingTasks.clear();
289 mRunningTasks.clear();
290 mCompletedTasks.clear();
293 void AsyncTaskManager::AddTask(AsyncTaskPtr task)
297 // Lock while adding task to the queue
298 Mutex::ScopedLock lock(mWaitingTasksMutex);
300 DALI_LOG_INFO(gAsyncTasksManagerLogFilter, Debug::Verbose, "AddTask [%p]\n", task.Get());
302 // push back into waiting queue.
303 auto waitingIter = mWaitingTasks.insert(mWaitingTasks.end(), task);
304 CacheImpl::InsertTaskCache(mCacheImpl->mWaitingTasksCache, task, waitingIter);
306 if(task->GetPriorityType() == AsyncTask::PriorityType::HIGH)
308 // Increase the number of waiting tasks for high priority.
309 ++mWaitingHighProirityTaskCounts;
314 Mutex::ScopedLock lock(mRunningTasksMutex); // We can lock this mutex under mWaitingTasksMutex.
316 // Finish all Running threads are working
317 if(mRunningTasks.size() >= mTasks.GetElementCount())
324 size_t count = mTasks.GetElementCount();
326 while(index++ < count)
328 auto processHelperIt = mTasks.GetNext();
329 DALI_ASSERT_ALWAYS(processHelperIt != mTasks.End());
330 if(processHelperIt->Request())
334 // If all threads are busy, then it's ok just to push the task because they will try to get the next job.
337 // Register Process (Since mTrigger execute too late timing if event thread running a lots of events.)
338 if(!mProcessorRegistered && Dali::Adaptor::IsAvailable())
340 Dali::Adaptor::Get().RegisterProcessor(*this);
341 mProcessorRegistered = true;
347 void AsyncTaskManager::RemoveTask(AsyncTaskPtr task)
351 DALI_LOG_INFO(gAsyncTasksManagerLogFilter, Debug::Verbose, "RemoveTask [%p]\n", task.Get());
353 // Check whether we need to unregister processor.
354 // If there is some non-empty queue exist, we don't need to unregister processor.
355 bool needCheckUnregisterProcessor = true;
358 // Lock while remove task from the queue
359 Mutex::ScopedLock lock(mWaitingTasksMutex);
361 auto mapIter = mCacheImpl->mWaitingTasksCache.find(task.Get());
362 if(mapIter != mCacheImpl->mWaitingTasksCache.end())
364 for(auto& iterator : mapIter->second)
366 DALI_ASSERT_DEBUG((*iterator) == task);
367 if((*iterator)->GetPriorityType() == AsyncTask::PriorityType::HIGH)
369 // Decrease the number of waiting tasks for high priority.
370 --mWaitingHighProirityTaskCounts;
372 mWaitingTasks.erase(iterator);
374 CacheImpl::EraseAllTaskCache(mCacheImpl->mWaitingTasksCache, task);
377 if(!mWaitingTasks.empty())
379 needCheckUnregisterProcessor = false;
384 // Lock while remove task from the queue
385 Mutex::ScopedLock lock(mRunningTasksMutex);
387 auto mapIter = mCacheImpl->mRunningTasksCache.find(task.Get());
388 if(mapIter != mCacheImpl->mRunningTasksCache.end())
390 for(auto& iterator : mapIter->second)
392 DALI_ASSERT_DEBUG((*iterator).first == task);
393 // We cannot erase container. Just mark as canceled.
394 // Note : mAvaliableLowPriorityTaskCounts will be increased after process finished.
395 (*iterator).second = RunningTaskState::CANCELED;
399 if(!mRunningTasks.empty())
401 needCheckUnregisterProcessor = false;
406 // Lock while remove task from the queue
407 Mutex::ScopedLock lock(mCompletedTasksMutex);
409 auto mapIter = mCacheImpl->mCompletedTasksCache.find(task.Get());
410 if(mapIter != mCacheImpl->mCompletedTasksCache.end())
412 for(auto& iterator : mapIter->second)
414 DALI_ASSERT_DEBUG(iterator->first == task);
415 mCompletedTasks.erase(iterator);
417 CacheImpl::EraseAllTaskCache(mCacheImpl->mCompletedTasksCache, task);
420 if(!mCompletedTasks.empty())
422 needCheckUnregisterProcessor = false;
426 // UnregisterProcessor required to lock mutex. Call this API only if required.
427 if(needCheckUnregisterProcessor)
429 UnregisterProcessor();
434 AsyncTaskPtr AsyncTaskManager::PopNextCompletedTask()
436 // Lock while popping task out from the queue
437 Mutex::ScopedLock lock(mCompletedTasksMutex);
439 AsyncTaskPtr nextCompletedTask = nullptr;
441 while(!mCompletedTasks.empty())
443 DALI_LOG_INFO(gAsyncTasksManagerLogFilter, Debug::Verbose, "PopNextCompletedTask, completed task count : [%zu]\n", mCompletedTasks.size());
445 auto next = mCompletedTasks.begin();
446 AsyncTaskPtr nextTask = next->first;
447 CompletedTaskState taskState = next->second;
448 CacheImpl::EraseTaskCache(mCacheImpl->mCompletedTasksCache, nextTask, next);
449 mCompletedTasks.erase(next);
451 DALI_LOG_INFO(gAsyncTasksManagerLogFilter, Debug::General, "Completed task [%p] (callback required? : %d)\n", nextTask.Get(), taskState == CompletedTaskState::REQUIRE_CALLBACK);
453 if(taskState == CompletedTaskState::REQUIRE_CALLBACK)
455 nextCompletedTask = nextTask;
460 DALI_LOG_INFO(gAsyncTasksManagerLogFilter, Debug::General, "Pickup completed [%p]\n", nextCompletedTask.Get());
462 return nextCompletedTask;
465 void AsyncTaskManager::UnregisterProcessor()
467 if(mProcessorRegistered && Dali::Adaptor::IsAvailable())
469 DALI_LOG_INFO(gAsyncTasksManagerLogFilter, Debug::Verbose, "UnregisterProcessor begin\n");
470 // Keep processor at least 1 task exist.
471 // Please be careful the order of mutex, to avoid dead lock.
472 // TODO : Should we lock all mutex rightnow?
473 Mutex::ScopedLock lockWait(mWaitingTasksMutex);
474 if(mWaitingTasks.empty())
476 Mutex::ScopedLock lockRunning(mRunningTasksMutex); // We can lock this mutex under mWaitingTasksMutex.
477 if(mRunningTasks.empty())
479 Mutex::ScopedLock lockComplete(mCompletedTasksMutex); // We can lock this mutex under mWaitingTasksMutex and mRunningTasksMutex.
480 if(mCompletedTasks.empty())
482 mProcessorRegistered = false;
483 Dali::Adaptor::Get().UnregisterProcessor(*this);
487 DALI_LOG_INFO(gAsyncTasksManagerLogFilter, Debug::Verbose, "UnregisterProcessor end (registed? %d)\n", mProcessorRegistered);
491 void AsyncTaskManager::TasksCompleted()
493 DALI_LOG_INFO(gAsyncTasksManagerLogFilter, Debug::Verbose, "TasksCompleted begin\n");
494 while(AsyncTaskPtr task = PopNextCompletedTask())
496 DALI_LOG_INFO(gAsyncTasksManagerLogFilter, Debug::Verbose, "Execute callback [%p]\n", task.Get());
497 CallbackBase::Execute(*(task->GetCompletedCallback()), task);
500 UnregisterProcessor();
501 DALI_LOG_INFO(gAsyncTasksManagerLogFilter, Debug::Verbose, "TasksCompleted end\n");
504 void AsyncTaskManager::Process(bool postProcessor)
509 /// Worker thread called
510 AsyncTaskPtr AsyncTaskManager::PopNextTaskToProcess()
512 // Lock while popping task out from the queue
513 Mutex::ScopedLock lock(mWaitingTasksMutex);
515 DALI_LOG_INFO(gAsyncTasksManagerLogFilter, Debug::Verbose, "PopNextTaskToProcess, waiting task count : [%zu]\n", mWaitingTasks.size());
517 // pop out the next task from the queue
518 AsyncTaskPtr nextTask = nullptr;
520 // Fast cut if all waiting tasks are LOW priority, and we cannot excute low task anymore.
521 if(mWaitingHighProirityTaskCounts == 0u && !mWaitingTasks.empty())
524 Mutex::ScopedLock lock(mRunningTasksMutex); // We can lock this mutex under mWaitingTasksMutex.
526 if(mAvaliableLowPriorityTaskCounts == 0u)
528 // There are no avaliabe tasks to run now. Return nullptr.
533 for(auto iter = mWaitingTasks.begin(), endIter = mWaitingTasks.end(); iter != endIter; ++iter)
535 if((*iter)->IsReady())
537 const auto priorityType = (*iter)->GetPriorityType();
538 bool taskAvaliable = priorityType == AsyncTask::PriorityType::HIGH; // Task always valid if it's priority is high
542 Mutex::ScopedLock lock(mRunningTasksMutex); // We can lock this mutex under mWaitingTasksMutex.
544 taskAvaliable = (mAvaliableLowPriorityTaskCounts > 0u); // priority is low, but we can use it.
553 // Lock while popping task out from the queue
554 Mutex::ScopedLock lock(mRunningTasksMutex); // We can lock this mutex under mWaitingTasksMutex.
556 DALI_LOG_INFO(gAsyncTasksManagerLogFilter, Debug::Verbose, "Waiting -> Running [%p]\n", nextTask.Get());
558 auto runningIter = mRunningTasks.insert(mRunningTasks.end(), std::make_pair(nextTask, RunningTaskState::RUNNING));
559 CacheImpl::InsertTaskCache(mCacheImpl->mRunningTasksCache, nextTask, runningIter);
561 CacheImpl::EraseTaskCache(mCacheImpl->mWaitingTasksCache, nextTask, iter);
562 mWaitingTasks.erase(iter);
564 // Decrease avaliable task counts if it is low priority
565 if(priorityType == AsyncTask::PriorityType::LOW)
567 // We are under running task mutex. We can decrease it.
568 --mAvaliableLowPriorityTaskCounts;
572 if(priorityType == AsyncTask::PriorityType::HIGH)
574 // Decrease the number of waiting tasks for high priority.
575 --mWaitingHighProirityTaskCounts;
582 DALI_LOG_INFO(gAsyncTasksManagerLogFilter, Debug::General, "Pickup process [%p]\n", nextTask.Get());
587 /// Worker thread called
588 void AsyncTaskManager::CompleteTask(AsyncTaskPtr&& task)
594 const bool needTrigger = task->GetCallbackInvocationThread() == AsyncTask::ThreadType::MAIN_THREAD;
596 // Lock while check validation of task.
598 Mutex::ScopedLock lock(mRunningTasksMutex);
600 auto mapIter = mCacheImpl->mRunningTasksCache.find(task.Get());
601 if(mapIter != mCacheImpl->mRunningTasksCache.end())
603 const auto cacheIter = mapIter->second.begin();
604 DALI_ASSERT_ALWAYS(cacheIter != mapIter->second.end());
606 const auto iter = *cacheIter;
607 DALI_ASSERT_DEBUG(iter->first == task);
608 if(iter->second == RunningTaskState::RUNNING)
610 // This task is valid.
615 DALI_LOG_INFO(gAsyncTasksManagerLogFilter, Debug::Verbose, "CompleteTask [%p] (is notify? : %d)\n", task.Get(), notify);
618 // We should execute this tasks complete callback out of mutex
619 if(notify && task->GetCallbackInvocationThread() == AsyncTask::ThreadType::WORKER_THREAD)
621 DALI_LOG_INFO(gAsyncTasksManagerLogFilter, Debug::Verbose, "Execute callback on worker thread [%p]\n", task.Get());
622 CallbackBase::Execute(*(task->GetCompletedCallback()), task);
625 // Lock while adding task to the queue
627 Mutex::ScopedLock lock(mRunningTasksMutex);
629 auto mapIter = mCacheImpl->mRunningTasksCache.find(task.Get());
630 if(mapIter != mCacheImpl->mRunningTasksCache.end())
632 const auto cacheIter = mapIter->second.begin();
633 DALI_ASSERT_ALWAYS(cacheIter != mapIter->second.end());
635 const auto iter = *cacheIter;
636 const auto priorityType = iter->first->GetPriorityType();
637 // Increase avaliable task counts if it is low priority
638 if(priorityType == AsyncTask::PriorityType::LOW)
640 // We are under running task mutex. We can increase it.
641 ++mAvaliableLowPriorityTaskCounts;
644 // Move task into completed, for ensure that AsyncTask destroy at main thread.
646 Mutex::ScopedLock lock(mCompletedTasksMutex); // We can lock this mutex under mRunningTasksMutex.
648 const bool callbackRequired = notify && (task->GetCallbackInvocationThread() == AsyncTask::ThreadType::MAIN_THREAD);
650 DALI_LOG_INFO(gAsyncTasksManagerLogFilter, Debug::Verbose, "Running -> Completed [%p] (callback required? : %d)\n", task.Get(), callbackRequired);
652 auto completedIter = mCompletedTasks.insert(mCompletedTasks.end(), std::make_pair(task, callbackRequired ? CompletedTaskState::REQUIRE_CALLBACK : CompletedTaskState::SKIP_CALLBACK));
653 CacheImpl::InsertTaskCache(mCacheImpl->mCompletedTasksCache, task, completedIter);
655 CacheImpl::EraseTaskCache(mCacheImpl->mRunningTasksCache, task, iter);
656 mRunningTasks.erase(iter);
658 // Now, task is invalidate.
664 // Wake up the main thread
667 DALI_LOG_INFO(gAsyncTasksManagerLogFilter, Debug::Verbose, "Trigger main thread\n");
673 // AsyncTaskManager::TaskHelper
675 AsyncTaskManager::TaskHelper::TaskHelper(AsyncTaskManager& asyncTaskManager)
676 : TaskHelper(std::unique_ptr<AsyncTaskThread>(new AsyncTaskThread(asyncTaskManager)), asyncTaskManager)
680 AsyncTaskManager::TaskHelper::TaskHelper(TaskHelper&& rhs)
681 : TaskHelper(std::move(rhs.mProcessor), rhs.mAsyncTaskManager)
685 AsyncTaskManager::TaskHelper::TaskHelper(std::unique_ptr<AsyncTaskThread> processor, AsyncTaskManager& asyncTaskManager)
686 : mProcessor(std::move(processor)),
687 mAsyncTaskManager(asyncTaskManager)
691 bool AsyncTaskManager::TaskHelper::Request()
693 return mProcessor->Request();
695 } // namespace Adaptor
697 } // namespace Internal