UE4 TaskGraph源码分析

2017-08-15  本文已影响0人  蛋求疼

TaskGraph Library

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

关键类

  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的任务。
    综上所述, 整个系统分两个部分:

GraphTask依赖网络

重点代码摘录:

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();
    
上一篇下一篇

猜你喜欢

热点阅读