Hexococos2dx 3.0 ---- Scheduler 2014-12-12
涉及到以下东西:
_listEntry (tListEntry)
1 | /* 用于全局的定时器 */ |
_hashUpdateEntry (tHashUpdateEntry)
1 | /* 全局定时器的hash */ |
_hashSelectorEntry (tHastTimeEntry)
1 | typedef struct _hashSelectorEntry |
对于名字不统一的解释:
- _hashSelectorEntry 给 TimerTargetSelector
- tHashTimerEntry 给 TimerTargetCallback
由于该结构体的计时器数组timers是保存着Ref*的数组,所以可以根据需要把timers中的元素强制转换成相应类型。
- Timer (TimerTargetSelector, TimerTargetCallback, 脚本)
- Scheduler
路径
1 | 2d/CCScheduler.h |
源码分析
我们需要先引用两个东西,详细可见cocos2dx 3.0 – Macros
1 | /* cpp11 回调函数 */ |
成员变量:
1 | class CC_DLL Scheduler : public Ref |
接着我们来看看主循环:
1 | void Scheduler::update(float dt) |
我们可以把Scheduler分成3部分:
- 系统级定时器,_updatesNegList,_updates0List,_updatesPosList
- 自定义定时器,TimerTargetCallback,TimerTargetSelector
- 其他线程的函数,_functionsToPerform
Selector
1 | template <class T> |
1 | void Scheduler::schedulePerFrame(const ccSchedulerFunc& callback, void *target, int priority, bool paused) |
appendIn和priorityIn的共同之处:
- 将元素添加到列表之中
- 更新_hashForUpdates这个hash表
Custom Selector
自定义定时器任务有两种类型:
- c/c++ 函数指针 – SEL_SCHEDULE
- std::function – ccSchedulerFunc
SEL_SCHEDULE
1 | void Scheduler::schedule(SEL_SCHEDULE selector, Ref *target, float interval, unsigned int repeat, float delay, bool paused) |
ccSchedulerFunc
其实这个和SEL_SCHEDULE实现很类似,只是在对定时器任务的类型有所区别。由于实现相似,所以这里就不贴代码了。
Function
这个部分就这么一小段代码,我看了下,cocos引擎里面自己是没有调用这个函数的。
1 | void Scheduler::performFunctionInCocosThread(const std::function<void ()> &function) |
总结
Scheduler的update函数是所有定时器任务,Action等等的最早的update。总结为以下三点:
- 具有全局任务,每一帧更新 – 三个双向链表,和一个hash表。
- 自定义任务,可以自定义时间间隔 – 一个
hash表 - 其他线程的函数 – 只能是void f()类型的函数