Modifying Data from with the Job System

Hello,

I’m currently trying out the job system, and I’m a bit confused by how to make it work. Basically, I’m trying to something like this in an IJob job:

public struct RenderJob: IJob
{
  public void Execute()
  {
    foreach(connectingNode in m_nodeData.connectedNodes)
    {
        m_nodeList.ListUpdate(connectingNode);
    }
  
    JobHandle.ScheduleBatchedJobs();
  }
 
  NodeData m_nodeData;  //this is only read
  NodeList m_nodeList;  //this list is updated and modified
}

public class NodeList
{
    public void Start()
    {
        RenderJob job = new RenderJob();
        //setup basic values here (first node, etc.)
        job.Schedule();
      
    }
  
    public void ListUpdate(connectingNode)
    {
        m_mutex.WaitOne();
        m_nodeList.Add(connectingNode);
        m_mutex.ReleaseMutex();
      
        RenderJob job = new RenderJob();
        job.m_nodeData = node;
        job.m_nodeList = this;

        job.Schedule();
    }
  
    HashSet<NodeData> m_listOfNodes;
    static Mutex m_mutex = new Mutex();
}

But it doesn’t seem to work. I either get errors regarding not being able to pass references, or see issues with trying to setup static data. Is there no way to modify data in unity jobs? I can do normal C# threading, but I assumed that would not be as safe or well-handled by Unity.

Thanks for anyone who knows how to get around this!

The job system works very differently from typical C# multithreading.

First off, you cannot pass reference (class) types in or out of a job. You have to use structs. If you need an array of something, use NativeArray. There are other Nativecontainers in the Collections package that also work with jobs.

Second, you cannot and should not use mutexes in jobs. The reason you can’t use reference types in jobs is because the job system has its own safety system which removes the need for mutexes.

That’s what I was afraid of. Sounds like I need to stick with traditional C# multithreading, although there might some way to do it less elegantly with the job system.