Search Unity

Feedback Managed components in parallel jobs

Discussion in 'Entity Component System' started by half_voxel, Dec 18, 2022.

  1. half_voxel

    half_voxel

    Joined:
    Oct 20, 2007
    Posts:
    978
    Currently, the entities package does not allow accessing managed components from multiple threads.
    I am wondering if there is any way to work around this, or if there are any plans for Unity to change this limitation?

    Of course, when possible everything should be using unmanaged components, but sadly there are cases where this is not possible (especially when integrating with existing codebases). Using the pure jobs system, I have previously solved this using GCHandles, which works perfectly fine as long as you take on the responsibility of ensuring there are no race conditions. However, despite my best efforts, I have not been able to find a similar workaround when using the entities package.
    Currently, my code spends more wall-clock-time doing single-threaded stuff using managed components than it does using highly parallelized and bursted systems. And I know that the managed components could easily be processed in parallel, but the entities package is preventing me from doing this. Managed components cannot even be used in *any* jobs at the moment. Which introduces a lot of sync points to the main thread in my code, and this adds latency.

    Does anyone else experience this problem, and are there any workarounds? If not, I propose to the entities team that there should be a workaround. Maybe an attribute similar to NativeDisableContainerSafetyRestrictionAttribute.
     
  2. DreamingImLatios

    DreamingImLatios

    Joined:
    Jun 3, 2017
    Posts:
    4,262
    GCHandles in unmanaged IComponentData is still probably the way to go. You can prevent object sharing by using a reactive pattern and storing your GCHandle inside an ICleanupComponentData. Those components are not copied when instantiating entities, so with the right queries and system, you can ensure that your GCHandles are always unique and are disposed properly.
     
    bb8_1 likes this.
  3. half_voxel

    half_voxel

    Joined:
    Oct 20, 2007
    Posts:
    978
    That's a nice pattern!
    Though, I am a bit worried about causing excessive fragmentation by using a bunch of long-lived GCHandles. Not a problem under mono, but might be with dotnetcore.