Reputation: 2191
On an iOS game I am making with Swift, I am listening to touch events, reading the userData
property of some SKNode
, and updating the texture property of some other SKSpriteNode
that are part of the scene, but to avoid any lag during the user interaction, I dispatch this update code asynchronously on the main queue, is it a good idea ?
By the way, some general question about thread safety : is there a risk only when you are writing data, or is there also a risk when reading data ?
Thank you.
Upvotes: 2
Views: 275
Reputation: 12001
As current documentation on SKNode
says in getting started section:
Ensure Node Access on the Main Thread
So, the answer for the question in the title
Is SKNode thread safe?
is - NO. SKNode
isn't thread safe, it should be modified only from the main thread.
But the answer for the second question:
I dispatch this update code asynchronously on the main queue, is it a good idea?
will be YES. It's exactly what you expected to do.
As for the last question: risk is possible when reading data. If you read a constant like let version = 3
, there will be no risk. But take a look at this example:
var bigLazyObject: BigObject?
func getBigLazyObject() -> BigObject {
if let existingObject = bigLazyObject {
return existingObject
} else {
let newObject = BigObject()
bigLazyObject = newObject
return newObject
}
}
It demonstrates an unwanted creation of the second BigObject
instance, which can occure if getBigLazyObject()
will be called in 2 threads simultaneously. There is a chance that both threads will fall in the else
branch of the if
statement before bigLazyObject
is actually created. This kind of problem should be solved when creating thread-safe singletons. In Swift they are thread-safe buy default, but in Objective-C people usually use dispatch_once()
block.
Upvotes: 1