Swift Guard Critical Sections of Concurrent Code (similar to mutex lock in c?)

143 Views Asked by At
func resetLobby() async {
    do {
        lobbyViewModel.pauseListener()
        let question = lobbyViewModel.currentLobby?.questionDeck?.currentQuestion
        if let winner, let question {
            print("Reset Lobby: ")
            try await lobbyViewModel.resetLobby(winner: winner, question: question)
        }
        try await lobbyViewModel.nextQuestion()
        lobbyViewModel.restartListener()
        // try await lobbyViewModel.nextQuestion()
        if let id = userViewModel.currentUser?.id, let num = lobbyViewModel.currentLobby?.number {
            try await userViewModel.loadUser(userId: id, lobbyNumber: num)
        }
    } catch {
        award = true
    }
}

I have an application with multiple users per lobby, with listeners attached to every user to update based on the lobby. Currently, the users fire while resetLobby is running, resulting in a race condition and incorrect attributes being returned to the users. Is there a Swift/async-friendly way to ensure that resetLobby() is treated as a block of code, and the listeners don't fire until resetLobby() is finished?

Note: The pause/start listeners work for the local listener, but not for the lobby-wide listeners.

0

There are 0 best solutions below