I have an huge array which contains a struct “Tile”. The program im writing is a 2D game, and I don’t want different players (handled by different threads) to write their position to the same tile at the same time, and I wondered two things. Can two threads write to two different places in the array at the same time safely, and is there some effective way to lock only one index of this array?
Share
Yes, you can write to different positions simultaneously from different threads.
To do the locking, you should create an array of locks, and use some simple hashing technique to choose a lock, based on the position being written. For instance:
This avoids the need to create zillions of locks, but still keeps lock-contention to a minimum. You can set numLocks up or down, based on profiling. Keep it a power of two, though, for an efficient modulo computation.
One final minutiae: beware of aliasing effects. For instance, multiple-of-16 positions might happen to be very popular with your threads for some odd reason, in which case, contention will go through the roof. If this is the case, you’ll need a stronger hash. Perhaps
(uint)i.GetHashCode() % numLockswill do, but I’m not sure whatInt32.GetHashCodedoes; it might just return the number itself. Failing this, you can steal one from Bob Jenkins.