I'm writing a turn-based game that processes the enemy AI on a background thread. I've never really done much with DispatchQueue, so this might be wrong, but this is what I'm doing...
private func takeTurnFor(actor: Actor) {
DispatchQueue.global(qos: .background).async {
let state = actor.brain.takeTurn(manager: manager)
EventManager.publish(event: AiTurnTaken(state: state))
}
}
This method is called from the main thread, once for each enemy actor, one at a time. My issue is that randomly the game will occasionally drop one or two frames/hang for 10-30ms when the AI task actually starts working, not every time but maybe one in five times.
My understanding is that the code in the closure above should be running on a separate thread, so how is it somehow causing the frame drops? I've modified the 'brains' to do basically no work at all, but still the issue happens.
You should really never use the .background QoS unless you want your work to be optional. I suggest starting with a single, dedicated serial queue with no special QoS and seeing how that performs.
So, it turns out the random lag spikes where the work was dispatched to a background queue were a total red herring - they do happen, but don't really cause noticeable visual issues, and are nothing to do with running on another thread, or seemingly anything to do with my code at all - perhaps they are something to do with the code running in debug mode on the simulator.
What was actually causing the stalls that caused the very noticeable visual stuttering where happening elsewhere entirely, and actually in the code that builds up the SKActions for animating an opponent's move once it has been decided, which happens on the main thread.
Thanks for the pointer @Jon_Shier , I'll do some more reading about dispatch queues.