void Scheduler::performFunctionInCocosThread(const std::function<void ()> &function)
{
_performMutex.lock();
_functionsToPerform.push_back(function);
_performMutex.unlock();
}
void Scheduler::update(float dt)
{
// xxxxxx ...
// Testing size is faster than locking / unlocking.
// And almost never there will be functions scheduled to be called.
if( !_functionsToPerform.empty() ) {
_performMutex.lock();
// fixed #4123: Save the callback functions, they must be invoked after '_performMutex.unlock()', otherwise if new functions are added in callback, it will cause thread deadlock.
auto temp = _functionsToPerform;
_functionsToPerform.clear();
_performMutex.unlock();
for( const auto &function : temp ) {
function();
}
}
}
1. do while(0)
2. vector的swap 释放vector已经分配的内存
vector的clear函数是无法释放掉已经分配好的内存的,但是swap一个空的vector是可以做到的。
3. DispatchGuard
利用临时变量的生命周期来更改变量,来判断函数是否还在执行。
4. 花里胡哨的位运算
找出比x大的2的幂次方数
5. 变长参数,最后一位为NULL来确定参数个数
6. 避免出现线程安全问题
7. C++11 智能指针的使用(shared_ptr week_ptr)
为了保证该变量在异步函数执期间不会被析构,可以传递一个指向自身的share_ptr给异步函数。
8. std::move 避免拷贝构造造成的浪费效率