Search Unity

Managed thread Temp/TempJob allocation safety

Discussion in 'Entity Component System' started by Zuntatos, Aug 31, 2020.

  1. Zuntatos

    Zuntatos

    Joined:
    Nov 18, 2012
    Posts:
    612
    Is it safe to alloc Temp/TempJob inside of a managed thread? I couldn't easily find any documentation on what the Temp/TempJob actually do, and when the temporary parts of it ends. I suspect only Persistent is safe in managed threads, unless you specifically start & finish within the unity callbacks (like a Parallel.For running in an Start). Would be great to have something more official/knowledgeable on this.
     
  2. burningmime

    burningmime

    Joined:
    Jan 25, 2014
    Posts:
    845
    The following is mostly found via experiments and stuff, so I'm not a reliable source.

    Temp is a thread-local bump allocator that has no way to deallocate (Dispose is a no-op):
    * When allocated inside a job, Temp lasts for the duration of the job
    * When allocated on the Unity Main thread, Temp lasts for the length of the frame
    * I wouldn't try it in a managed thread other than Unity's main thread, but YMMV

    TempJob allocates from a buffer pool. I don't know all the details, but it likes to complain if allocations are more than 4 frames old, so I guess it marks them with a frame counter. AFAICT, TempJob allocations are not thread-safe at all, they must happen from the Unity main thread (or maybe internal threads).

    Persistent should be fine, I think it's just a wrapper around
    malloc
    .
     
    Zuntatos likes this.