On the server application, I need to assign to each connected client an unique ID, so I am doing it this way:
private short GetFreeID()
{
lock (this.mUsedPlayerIDsSynchronization)
{
for (short I = 1; I < 500; I++)
{
if (ClientIDPool[I] == false)
{
ClientIDPool[I] = true;
return I;
}
}
return -1;
}
}
My first question: Could it be done more efficiently, I mean with better performance? I have read here that we should learn to write code without locks. I have also read there for some atomic operations there are other options.
Second question: What if I wanted to lock the whole class in order to do not allow to make any changes within? For example: one client will update second clients data, can I lock the whole second client class that it is absolutely blocked? I still think “lock” will only make sure that code inside its snippet is entered by only one thread at the time, so I do not know if “lock(client2)” causes that nothing in that class can be changed until this lock is released.
Locks are often the simplest way of getting things right, which is very important. Quite often it doesn’t matter if there’s a more efficient way of doing things, so long as you’ve got clear code and it performs well enough.
A more performant approach here, however, would be to either generate a random GUID, or if you do want to reuse IDs, have a “pool” (e.g. a
LinkedList) of unused IDs. You could then take from the pool very quickly, and return the ID to the pool (again quickly) once you’re done.Alternatively, if you really just need an integer and it doesn’t have to be a low one, you could have a static variable which starts at 0 and which you just increment each time – you can do this without locking using
Interlocked.Incrementshould you wish. I doubt that you’ll run out of 64-bit integers, for example 🙂As for your second question: yes, locks are advisory. If everything within the class takes out the same lock before changing any fields (and the fields are private) then that prevents other code from misbehaving… but each bit of code does need to take out the lock.
EDIT: If you really only need an integer, I would still suggest just using
Interlocked.Increment– even if your traffic increases 1000-fold, you could use a 64 bit integer instead. However, if you want to reuse IDs then I’d suggest creating a new type to represent the “pool”. Give that a counter of how many have been created, so that if you run out you can assign a new item. Then just store the available ones in aQueue<int>,LinkedList<int>orStack<int>(it’s not going to matter very much which you use). Assuming you can trust your own code to return IDs sensibly, you can make the API as simple as:AllocateIDwould check to see if the pool is empty, and allocate a new ID if so. Otherwise, it would just remove the first entry from the pool and return that.ReturnIDwould just add the specified ID to the pool.