1

I'm developping a multiplayer game and I want to connect two players that don't know each other with a research in the database. So I thinked about doing it like this:

  • The player that want to play with a random opponent clicks a button on my app.
  • When the button is pressed I control in the database in my 'randomPlayers' table if there is someone to play with
  • If there aren't player stored in the table I put the nickname in the database waiting for someone that want to play
  • If, instead, there is someone stored in the database I take the first nickname (ordered by timestamp) and I play with it.

My question is: How I can be sure that two players that search a random player in the same moment take two differents players and not the same because SELECT return the same player ? In other words is SELECT synchronous or asynchronous ?

Matteo Cardellini
  • 876
  • 2
  • 17
  • 41

1 Answers1

1

I hope you are doing a 3 tier design, and not 2 tier. E.g. does the program connect to a server in the middle which connects to the database (3 tier), or does the program connect directly to the database (2 tier)?

If 2 tier, you may have to wrap the select in some kind of transaction that grabs the player and updates the table so that a second request won't grab the same player. Side note, you may want to consider switching to a 3 Tier design to give yourself better management over what users can and cannot do to your database.

If 3 tier, you can probably avoid this all together by using some kind of locking system provided by the language you are using to build the server in the middle. Most modern programming languages now provide some syntax that allows you to specify that only one thread should run a given piece of code at a time, allowing you to manage these kinds of concurrency issues.

Also consider this question on MySQL concurrency

Community
  • 1
  • 1
William Leader
  • 814
  • 6
  • 20
  • Yes of course i use a 3 tier. My application communicate via WebService to a PHP page that read and write in a MySql database and then I take a reply from the webservice to my application. In this case how can I do that ? – Matteo Cardellini Mar 19 '14 at 12:40
  • Since PHP doesn't really do multithreading (two requests to the database shouldn't be running at the same time), putting multiple SQL statements into a transaction should be sufficient. something like this pseudo sql: START TRANSACTION; SELECT Player; UPDATE player; --or delete? You know your tables better than me. COMMIT; – William Leader Mar 19 '14 at 12:46
  • But If PHP is not multithread there is no danger of a very slow answer from the database when A LOT of users request the same thing at the same time ? – Matteo Cardellini Mar 19 '14 at 12:50
  • I'm not sure. This question is moving beyond my expertise. You might consider adding a PHP tag to the question to attract people with that experience. – William Leader Mar 19 '14 at 15:46