cocos2d::Ref Multithreading

Is it possible to use objects inherited from cocos2d::Ref on a background Thread?

I’d like to put the simulation of my game on a background thread which uses objects inherited from cocos2d::Ref.

But since the autorelease pool is on another thread, this is likely to cause problems.

So, what’s the solution to this problem?

You are right, this is not safe to do.

You can make objects, manipulate them, schedule the changes, but you eventually need to do something like: Director::getInstance()->getScheduler()->performFunctionInCocosThread

Can anyone else chime in with feedback about this?

Thanks for the fast response!

I mainly want to use the collections Map and Array, as it is really convenient to remove something from a Collection and not having to delete the object manually.

When not using autorelease at all, it should be safe to do it on another thread, right?

Yes.

Do you really need the autopool containers?

You could just use the STL containers combined with the C++11 smart pointers.
The containers offer the same functionality and you can easily implement your multi-threading needs.

Well, I’m not really familiar with the STL containers and smart pointers, but it might a good idea to learn them.
I come from Objective-C, so the release() / retain() mechanism makes a lot of sense to me, and the cocos2d-containers are modeled after the containers I know from there.

So which containers would have a similar behaviour?
Hence, when removing an object from them, the object gets deallocated just like with cocos2d::Map and cocos2d::Vector.

If anybody can show me a minimal example of how this works, I’ll be gladly going this way.

std::map and std::vector.

cocos2d::Map and cocos2d::Vector are just using the STL containers under the hood.

Yes. The same happens when using the STL containers and C++11 smart pointers.

By using the smart pointers of C++11, you basically get rid of any new/delete pair.

This is a nice read about applying smart pointers to STL containers, including modified compare functions:
http://eli.thegreenplace.net/2012/06/20/c11-using-unique_ptr-with-standard-library-containers

If you want to learn about that stuff, you should read the blog from Herb Sutter:

Thank you!

I just replaced my first pointers with smart pointers!

1 Like