Search Unity

Question Multithreading / Tasks / Jobs in Unity 2019 and 2020 and future releases

Discussion in 'Scripting' started by devluz, Dec 19, 2021.

  1. devluz

    devluz

    Joined:
    Aug 20, 2014
    Posts:
    66
    What is the current state multithreading in Unity?I find a lot of conflicting information online and I am not sure what is the right technology to use to ensure stability and future support by Unity.

    My scenario looks like the following using Unity 2019 LTS:
    1. Get data from within Unity (from the GPU via AsyncGPUReadbackRequest). Not every frame but as often as possible.
    2. Hand off the data to via a C# API to C++ (via NativeArray / unsafe ptr)
    3. Store the results in a file

    The whole process might take 20-40ms so doing it within Unity's Update loop wouldn't be an option.
    Edit: Also note the whole process is low priority. It shouldn't lead to major FPS drops

    My option I see so far are:
    a) Spawn my own System.Threading.Thread and do the tricky bits myself. Downside is there is high risk of causing bugs and I spawn yet another thread (and there seem to be already tons running in any given Unity app)
    b) Use C# ThreadPool . Not really that different than a) I suppose but at least something else can more efficiently manage the threads.
    c) Using C# Tasks. They seem suitable for my needs but don't seem to be recommended in Unity
    d) Using Unity's C# Job System. I haven't used these yet but it looks like they are meant to be used to do the processing via C# & Burst. This doesn't seem to help me given that I have to pass the data into C++ via an existing C# wrapper and also have to access other managed C# calls. The documentation also mentions it will copy the NativeArray I process at which point I would loose tons of performance ...

    In general it looks to me like I could use all four of these. But what is the actual recommended way of doing this in modern Unity? Does anyone have experience with similar use-cases?