Mutexes for NativeMultiHashMap

Are mutexes needed for writes to and reads from Native data types, especially those used in IJobParallelFor? Something like in this:

[BurstCompile]
    private struct FilterJob : IJobParallelFor
    {
        public NativeArray<Vector3> currentStarts ;
        public NativeHashMap<int, int> remaining;
        public NativeArray<RaycastHit> results;
        public NativeMultiHashMap<int, RaycastHit> allHits;
        public NativeArray<Vector3> ends;

        public void Execute(int index)
        {
            int value = 0;
            if (remaining.TryGetValue(index, out value))
            {
                RaycastHit hit = results[index];
                if(hit.point == default(Vector3))
                {
                    remaining.Remove(index);
                }
                else
                {
                    allHits.Add(index, hit);
                    currentStarts[index] = results[index].point + (ends[index] - currentStarts[index]).normalized * 0.1f;
                }
            }
        }
    }

A lot of native containers have concurrent versions which let you write i parallel safely.

NativeQueue.Concurrent
NativeHashMap<TK, TV>.Concurrent
NativeMultiHashMap<TK, TV>.Concurrent

To use this, just convert a regular queue to it’s concurrent representation.

var queue = new NativeQueue<T>()

var job = new Job
{
    Queue = queue.ToConcurrent(),
}

Concurrent versions are write only. You can not read for them.

To read in parallel, you can mark the container as [ReadOnly], for example.

[ReadOnly]
public NativeArray<Vector3> currentStarts

In which case you can obviously not write to the array.

2 Likes