I'm attempting to write a random-code generator that will return a 5-character code to a client (for example, '8xc55'). I'd like this code to be unique, so I'm planning on storing it in a MySQL database, along with some other related data. When the script is run, it should generate a new code, confer with the database to make sure that code doesn't already exist, and return the code. If the code does exist, the script loops until it's generated a unique code. (Note that the codes will get thrown out after a certain amount of time, so I'm not worried about using up all the possible codes.)
The problem I'm thinking I'll have is with concurrency. Say a bajillion clients access the script at the same time (I can dream, right?
Code: Select all
lock();
while (true)
{
newCode = generateNewCode();
if (codeDoesntAlreadyExist(newCode))
break;
}
writeCodeToDatabase(newCode);
unlock();
Thanks a lot for any insight!
David