Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

Is NativeBitArray threadsafe?

Discussion in 'Entity Component System' started by Pyromuffin, Dec 31, 2020.

  1. Pyromuffin

    Pyromuffin

    Joined:
    Aug 5, 2012
    Posts:
    85
    Pretty simple question: can I set or clear bits from multiple job threads simultaneously?

    Looking at the source in the package it doesn't seem like it's thread safe, as there's no locking or atomics going on, but the description of Unity.Collections is that these containers are meant to be used with jobs. So, which is it?
     
  2. Pyromuffin

    Pyromuffin

    Joined:
    Aug 5, 2012
    Posts:
    85
    Well, answered my own question by trying it. it's not.
     
  3. Sarkahn

    Sarkahn

    Joined:
    Jan 9, 2013
    Posts:
    440
    For future reference if a container is writable from multiple thread it will have an
    AsParallelWriter
    method which will return a wrapper that is safe to use in parallel jobs. Most native containers have it, but not NativeBitArray apparently
     
    Pyromuffin likes this.
  4. Pyromuffin

    Pyromuffin

    Joined:
    Aug 5, 2012
    Posts:
    85
    I was thinking it would work like NativeArray, where you can safely write to it as long as the indices are within the permitted range.
     
  5. desertGhost_

    desertGhost_

    Joined:
    Apr 12, 2018
    Posts:
    246
    You could try using NativeDisableParallelForRestriction, but intentionally writing to the same data structure (that is not a parallel writer) from multiple threads is not a good idea. I would recommend using a NativeStream or some other data structure that supports parallel writing to queue changes in parallel and then apply them in a singlethreaded job.

    Unity's safety system is designed in a way to prevent race conditions. Incorrect use of locks can lead to a deadlock, so instead "[t]he C# Job System solves this by sending each job a copy of the data it needs to operate on, rather than a reference to the data in the main thread. This copy isolates the data, which eliminates the race condition."
     
  6. Pyromuffin

    Pyromuffin

    Joined:
    Aug 5, 2012
    Posts:
    85
    I'll look into NativeStream, but at the very minimum not using a bit array would increase my bandwidth by 8x, so that's a pretty crappy tradeoff.
     
  7. Pyromuffin

    Pyromuffin

    Joined:
    Aug 5, 2012
    Posts:
    85
    I'm going to try to emulate it with an array of UnsafeAtomicCounter64, however, these are longs, and not ulongs, so I might have to get spicy with the sign bit.