What is the use case of IJobFor when IJobParallelFor exists?

Different job types: Unity - Manual: Jobs overview

It says that IJobParallelFor runs a task in parallel, ie on multiple worker threads. So clearly each Execute(int index) must be independent from others.

And IJobFor runs on a single worker thread. They both have Execute(int index).

Now, I initially thought that since IJobFor runs on a single worker thread, I could e.g increment some global variable in every Execute() to track how many Execute()s have already been run.

But that is not possible, as the Execute()s may run on multiple cores.

The Unity page for IJobFor says:

Each iteration must be independent from other iterations and the safety system enforces this rule for you. The indices have no guaranteed order and are executed on multiple cores in parallel.

Here: https://docs.unity3d.com/ScriptReference/Unity.Jobs.IJobFor.html#:~:text=Each%20iteration%20must%20be%20independent%20from%20other%20iterations%20and%20the%20safety%20system%20enforces%20this%20rule%20for%20you.%20The%20indices%20have%20no%20guaranteed%20order%20and%20are%20executed%20on%20multiple%20cores%20in%20parallel.

So what is the use case for IJobFor if it runs on a single worker thread and I each iteration must be independent from each other?

IJobParallelFor came first. It has a scheduling extension method Schedule which schedules things in parallel.

At some point, job interfaces started to standardize on a pattern where ScheduleParallel is used as the extension method name for scheduling jobs to potentially run on multiple workers at once, while Schedule is used for single-threading a job.

IJobFor is one such job interface, and allows for specifying Schedule or ScheduleParallel for single or multi-worker scheduling. Similar to IJobChunk/IJobEntity in the Entities package, this allows one to use one job interface for a category of operations and adjust invocation to use Run/Schedule/ScheduleParallel as necessary. The need typically comes from using main-thread-only things like UnityEngine.Object-derived types (need Run), or single-thread-only access like non-ParallelWriter collections (need Run or Schedule).

IJobFor fits nicely with other jobs used these days, and there’s not much reason to keep using IJobParallelFor when IJobFor fills that role and more.

2 Likes