1

In a SpriteKit game I am developing I get multiple warnings from the Thread Sanitizer.

There are some properties of some sprites as well as of the GameScene that are updated asynchronuosly by the player's interaction, for example the player's speed.

These values, of course, will be read by other parts of the code, for example in the scene's .update method.

For some of the more often called properties I wrote a getter/setter method to sync the access to the data like this:

class PoliceSprite: SKSpriteNode {

    private var _policeSpeed: CGFloat = 0

    private var accessQueue = DispatchQueue(label: "policeAccessQueue", qos: .userInteractive, attributes: .concurrent)

    var policeSpeed: CGFloat {
    
        get {
            var returnValue: CGFloat = 0
            accessQueue.sync {
                returnValue = _policeSpeed
            }
            return returnValue
        }
    
        set {
            accessQueue.async(flags: .barrier) {
                self._policeSpeed = newValue
            }
        }
    }
}

But I wonder if I'd have to do that with every single value in the code - it looks clumsy, and I haven't come across any sample or tutorial code with such a large amount of synchronisation effort necessary.

My question:

Is there a best practice how game stats are dealt with in a thread-safe way? Maybe even a feature in the SpriteKit API I'm not aware of?

MassMover
  • 529
  • 2
  • 17
  • I'm pretty certain that `touchesBegan` etc. run along with (and on the same thread as) the update loop, and I've never noticed any synchronization problems. Are you doing stuff on other threads that may affect the game state (e.g., not using SpriteKit actions but GCD or something)? – bg2b Dec 21 '21 at 00:13

0 Answers0