UE4 TaskGraph源码分析

TaskGraph Library

TaskGraph用于实现将将多个Taskes放入多个线程执行,并且可以设定这些Task之间的依赖。引擎很多模块用到了它。现在我们就来解读一下它的实现,文章后部分再进行使用案例分析。
源码路径:

  • Engine\Source\Runtime\Core\Public\Async\TaskGraphInterfaces.h
  • Engine\Source\Runtime\Core\Private\Async\TaskGraph.cpp

关键类

  1. FTaskGraphInterface
    Interface tot he task graph system.
  2. FBaseGraphTask
    Base class for all tasks.
  3. FGraphEvent
    A FGraphEvent is a list of tasks waiting for something. These tasks are call the subsequents. A graph event is a prerequisite for each of its subsequents. Graph events have a lifetime managed by reference counting.
  4. template< typename TTask> class TGraphTask
    Embeds a user defined task, as exemplified above, for doing the work and provides the functionality for setting up and handling prerequisites and subsequents.
  5. FReturnGraphTask
    a task used to return flow control from a named thread back to the original caller of ProcessThreadUntilRequestReturn.
  6. FNullGraphTask
    a task that does nothing. It can be used to "gather" tasks into one prerequisite.
  7. FTriggerEventGraphTask
    a task that triggers an event(operating system Event object)
  8. FSimpleDelegateGraphTask
    for simple delegate based tasks. This is less efficient than a custom task, doesn't provide the task arguments, doesn't allow specification of the current thread, etc.
  9. FDelegateGraphTask
    class for more full featured delegate based tasks. Still less efficient than a custom task, but provides all of the args.
  10. FFunctionGraphTask
    Task class for lambda based tasks.
  11. FCompletionList
    List of tasks that can be "joined" into one task which can be waited on or used as a prerequisite.

经过分析源码,得出如下设计思路:

  1. 一个TaskGraph对象会依赖多个GraphEvent对象, 也就是说该TaskGraph对象在收到所有先决事件触发后,才能执行任务;
  2. 一个TaskGraph对象执行任务后,会触发它的GraphEvent, GraphEvent会尝试唤醒依赖于它的Task。
  3. FTaskGraphInterface的实现负责执行TaskGraph的任务。
    综上所述, 整个系统分两个部分:
  • TaskGraph和GraphEvent组成了Task依赖网络(当然不能出现循环依赖);
  • FTaskGraphInterface的实现负责执行TaskGraph的任务,安排这些任务在某些线程上运行。

GraphTask依赖网络

重点代码摘录:

  • FGraphEvent
    class FGraphEvent
    {
     public:
         bool AddSubsequent(class FBaseGraphTask* Task)
         {
             return SubsequentList.PushIfNotClosed(Task);
         }
    
         /**
          *  Delay the firing of this event until the given event fires.
          *  CAUTION: This is only legal while executing the task associated with this event.
          *  @param EventToWaitFor event to wait for until we fire.
         **/
         void DontCompleteUntil(FGraphEventRef EventToWaitFor)
         {
             checkThreadGraph(!IsComplete()); // it is not legal to add a DontCompleteUntil after the event has been completed. Basically, this is only legal within a task function.
             new (EventsToWaitFor) FGraphEventRef(EventToWaitFor);
         }
    
         /**
          *  "Complete" the event. This grabs the list of subsequents and atomically closes it. Then for each subsequent it reduces the number of prerequisites outstanding and if that drops to zero, the task is queued.
          *  @param CurrentThreadIfKnown if the current thread is known, provide it here. Otherwise it will be determined via TLS if any task ends up being queued.
         **/
         CORE_API void DispatchSubsequents(TArray<FBaseGraphTask*>& NewTasks, ENamedThreads::Type CurrentThreadIfKnown = ENamedThreads::AnyThread);
    
         bool IsComplete() const
         {
             return SubsequentList.IsClosed();
         }
    
     private:
    
         /** Threadsafe list of subsequents for the event 依赖于该事件的任务列表 **/
         TClosableLockFreePointerListUnorderedSingleConsumer<FBaseGraphTask, 0>      SubsequentList;
         /** List of events to wait for until firing. This is not thread safe as it is only legal to fill it in within the context of an executing task. 附加的等待事件数组 **/
         FGraphEventArray                                                        EventsToWaitFor;
         /** Number of outstanding references to this graph event **/
         FThreadSafeCounter                                                      ReferenceCount;
     };
    
  • FBaseGraphTask
     class FBaseGraphTask
     {
     public:
         FBaseGraphTask(
             int32 InNumberOfPrerequistitesOutstanding
             )
             : ThreadToExecuteOn(ENamedThreads::AnyThread)
             , NumberOfPrerequistitesOutstanding(InNumberOfPrerequistitesOutstanding + 1) // + 1 is not a prerequisite, it is a lock to prevent it from executing while it is getting prerequisites, one it is safe to execute, call PrerequisitesComplete
         {
             checkThreadGraph(LifeStage.Increment() == int32(LS_Contructed));
         }
         
         void PrerequisitesComplete(ENamedThreads::Type CurrentThread, int32 NumAlreadyFinishedPrequistes, bool bUnlock = true)
         {
             checkThreadGraph(LifeStage.Increment() == int32(LS_PrequisitesSetup));
             int32 NumToSub = NumAlreadyFinishedPrequistes + (bUnlock ? 1 : 0); // the +1 is for the "lock" we set up in the constructor
             if (NumberOfPrerequistitesOutstanding.Subtract(NumToSub) == NumToSub) 
             {
                 QueueTask(CurrentThread);
             }
         }
         void ConditionalQueueTask(ENamedThreads::Type CurrentThread)
         {
             if (NumberOfPrerequistitesOutstanding.Decrement()==0)
             {
                 QueueTask(CurrentThread);
             }
         }
    
         // Subclass API
         FORCEINLINE void Execute(TArray<FBaseGraphTask*>& NewTasks, ENamedThreads::Type CurrentThread)
         {
             checkThreadGraph(LifeStage.Increment() == int32(LS_Executing));
             ExecuteTask(NewTasks, CurrentThread);
         }
         // Internal Use
         void QueueTask(ENamedThreads::Type CurrentThreadIfKnown)
         {
             checkThreadGraph(LifeStage.Increment() == int32(LS_Queued));
             FTaskGraphInterface::Get().QueueTask(this, ThreadToExecuteOn, CurrentThreadIfKnown);
         }
    
         /** Thread to execute on, can be ENamedThreads::AnyThread to execute on any unnamed thread **/
         ENamedThreads::Type         ThreadToExecuteOn;
         /** Number of prerequisites outstanding. When this drops to zero, the thread is queued for execution.  **/
         FThreadSafeCounter          NumberOfPrerequistitesOutstanding; 
     };
    
  • TGraphTask
      /** 
      *  TGraphTask
      *  Embeds a user defined task, as exemplified above, for doing the work and provides the functionality for setting up and handling prerequisites and subsequents
      **/
     template<typename TTask>
     class TGraphTask : public FBaseGraphTask
     {
     public:
         virtual void ExecuteTask(TArray<FBaseGraphTask*>& NewTasks, ENamedThreads::Type CurrentThread) final override
         {
             checkThreadGraph(TaskConstructed);
    
             // Fire and forget mode must not have subsequents
             // Track subsequents mode must have subsequents
             checkThreadGraph(XOR(TTask::GetSubsequentsMode() == ESubsequentsMode::FireAndForget, IsValidRef(Subsequents)));
    
             if (TTask::GetSubsequentsMode() == ESubsequentsMode::TrackSubsequents)
             {
                 Subsequents->CheckDontCompleteUntilIsEmpty(); // we can only add wait for tasks while executing the task
             }
    
             TTask& Task = *(TTask*)&TaskStorage;
             {
                 FScopeCycleCounter Scope(Task.GetStatId(), true); 
                 Task.DoTask(CurrentThread, Subsequents);
                 Task.~TTask();
                 checkThreadGraph(ENamedThreads::GetThreadIndex(CurrentThread) <= ENamedThreads::RenderThread || FMemStack::Get().IsEmpty()); // you must mark and pop memstacks if you use them in tasks! Named threads are excepted.
             }
    
             TaskConstructed = false;
    
             if (TTask::GetSubsequentsMode() == ESubsequentsMode::TrackSubsequents)
             {
                 FPlatformMisc::MemoryBarrier();
                 Subsequents->DispatchSubsequents(NewTasks, CurrentThread);
             }
    
             if (sizeof(TGraphTask) <= FBaseGraphTask::SMALL_TASK_SIZE)
             {
                 this->TGraphTask::~TGraphTask();
                 FBaseGraphTask::GetSmallTaskAllocator().Free(this);
             }
             else
             {
                 delete this;
             }
         }
         
         /** An aligned bit of storage to hold the embedded task **/
         TAlignedBytes<sizeof(TTask),ALIGNOF(TTask)> TaskStorage;
         /** Used to sanity check the state of the object **/
         bool                        TaskConstructed;
         /** A reference counted pointer to the completion event which lists the tasks that have me as a prerequisite. **/
         FGraphEventRef              Subsequents;  //该任务执行完,需要激发该事件对象
    };
    

GraphTask与Event组成任务执行依赖网络, 注意Event对象是可以动态绑定到一个GraphTask上的,但是根据设计需求同一时刻只能只能绑定到一个GraphTask上,
这个妙用请参阅

void FGraphEvent::DispatchSubsequents(TArray<FBaseGraphTask*>& NewTasks, ENamedThreads::Type CurrentThreadIfKnown = ENamedThreads::AnyThread)

的实现。
依赖网络图解:


TaskGraph_Library.jpg

任务的调度执行

class FTaskGraphInterface负责对GraphTask的调度执行,它根据GraphTask的要求安排到希望的线程上去执行。细节请阅读它的实现代码。调试如下使用案例

  1. FRenderCommandFence类
     // Issue a fence command to the rendering thread and wait for it to complete.
     FRenderCommandFence Fence;
     Fence.BeginFence();
     Fence.Wait();
    
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,175评论 5 466
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,674评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,151评论 0 328
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,597评论 1 269
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,505评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,969评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,455评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,118评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,227评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,213评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,214评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,928评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,512评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,616评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,848评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,228评论 2 344
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,772评论 2 339

推荐阅读更多精彩内容

  • 出入无人识,进场撒满地。 不肯与君见,只怕留下恨。
    我爱吃任何鱼阅读 149评论 0 2
  • 晚间跟隔壁的叔叔阿姨聊天,说讲白话的故事,说身体的病痛,谈关于年龄的趣事 …… 阿姨说她上学的时候...
    小社工阅读 321评论 2 1
  • 【作者】陈天歌 【导师】刘艳 袁浩 郑鹏 【导图解说】这幅导图,画的是七年级下册,第20课中的第一首古诗文,《登幽...
    天蓝的海阅读 594评论 0 1