Are global variables thread safe?

Are global variables thread safe?

I have a global 2D array that keeps track of what tiles of the game are occupied. Many different scripts modify this array. Will I run into any race conditions?


Your global variable are not thread safe.
But since Unity engine is mono-thread for all the game stuff, you don’t need to worry about it.

BUT, if you do your own calculations on a thread different from the main thread, yes, you must be careful and start to lock and put fences everywhere it is required.

Remember only the main thread is allowed to touch Object!

Unity3D methods are not thread-safe. However any ‘static’ field you make will be thread-safe after you use some of your System.Threading skills.

With this being said, using a static field as a wrapper for a Unity3D method may yield… unexpected results.

‘Atomic’ means thread safe, see here:

No they are not. You need to lock the array any time you read/write to it. This should do the trick:

public class TileManager
    private Tile[] m_Tiles;
    public Tile this[int i]
        get { lock(m_Tiles) { return m_Tiles; } }
        set { lock(m_Tiles) { m_Tiles = value; } }

You also need to make sure you do not try to assign to the private array without a lock statement. Note that the getter does not lock the actual Tile object, only the array, so any operations on the Tile object will not be safe unless you lock it.

To address the problem mentioned in the comment below - if you are not creating your own threads, then you are safe and do not need to do any of this. Without concurrency there are not race conditions.*_