0
\$\begingroup\$

I'm trying to create a simple node app utilizing socket.io rooms where users can play a 1v1 game against other users. The system I have in place at the moment is when a user clicks the play button they are put into a queue. Once the queue reaches 2 players the first 2 players in the queue are matched and redirected to a game.

function socketHandler(socket){
    const db=dbGetter.getDb()
    socket.on('joinQueue',()=>{
        queue.push(socket)
        if(queue.length>=2){
            playerOneSocket=queue.shift()
            playerTwoSocket=queue.shift()
            CreateGameBySockets(playerOneSocket,playerTwoSocket,db,(game)=>{
                //redirects players to game not yet implemented
            })
        }
    })
}

This code works as intended as far as I can tell (Once the queue reaches 2 createGameBySockets is triggered and queue is cleared). However, I have concerns about how it will function with many users joining the queue in quick succession. For instance, say ten users attempt to join the queue simultaneously. I worry that the queue.shift() lines won't be triggered fast enough and multiple games will be created between the first 2 players in the queue before they are removed from the queue

I'm not sure of a way that I can test for such a scenario. Looking for advice on how to prevent this scenario from occurring and how I could test to see how this scenario would be handled.

\$\endgroup\$
1
  • \$\begingroup\$ Your question voices concerns about "racy data access". The usual response would be to wrap a lock around such accesses. Please review the standard advice and let us know about the implementation you settled on. \$\endgroup\$
    – J_H
    Jan 29 at 2:49

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.