版本:Unity 6 (6000.0)
语言英语
  • C#

IJobParallelFor

Unity.Jobs 中的接口

建议修改

成功!

感谢您帮助我们提高 Unity 文档的质量。虽然我们无法接受所有提交,但我们确实会阅读用户提出的每一项修改建议,并在适用的情况下进行更新。

关闭

提交失败

由于某些原因,您的修改建议无法提交。请<a>稍后再试</a>。感谢您抽出时间帮助我们提高 Unity 文档的质量。

关闭

取消

描述

表示一个作业的接口,该作业对原生容器的每个元素或固定数量的迭代执行相同的独立操作。

当您调度一个 IJobParallelFor 作业时,其 Execute(int index) 方法将在多个工作线程上并行调用。

Execute(int index) 从 0 到提供的长度对每个索引执行一次。每次迭代必须独立于其他迭代,并且安全系统会为您强制执行此规则。索引没有保证的顺序,并且会在多个内核上并行执行。

Unity 会自动将工作分成不小于提供的 batchSize 的块,并根据工作线程数、数组长度和批次大小调度适当数量的作业。根据作业中执行的工作量选择批次大小。例如,一个简单的作业(将几个 Vector3 相加)应该具有 32 到 128 的批次大小。但是,如果执行的工作非常昂贵,则最好使用较小的批次大小,例如批次大小为 1。IJobParallelFor 使用原子操作来执行工作窃取。批次大小可以很小,但它们不是免费的。

您可以使用返回的 JobHandle 来确保作业已完成,或者您可以将其作为依赖项传递给其他作业,以确保作业在工作线程上一个接一个地执行。

using UnityEngine;
using Unity.Collections;
using Unity.Jobs;

class ApplyVelocityParallelForSample : MonoBehaviour { struct VelocityJob : IJobParallelFor { // Jobs declare all data that will be accessed in the job // By declaring it as read only, multiple jobs are allowed to access the data in parallel [ReadOnly] public NativeArray<Vector3> velocity;

// By default containers are assumed to be read & write public NativeArray<Vector3> position;

// Delta time must be copied to the job since jobs generally don't have concept of a frame. // The main thread waits for the job same frame or next frame, but the job should do work deterministically // independent on when the job happens to run on the worker threads. public float deltaTime;

// The code actually running on the job public void Execute(int i) { // Move the positions based on delta time and velocity position[i] = position[i] + velocity[i] * deltaTime; } }

public void Update() { var position = new NativeArray<Vector3>(500, Allocator.Temp);

var velocity = new NativeArray<Vector3>(500, Allocator.Temp); for (var i = 0; i < velocity.Length; i++) velocity[i] = new Vector3(0, 10, 0);

// Initialize the job data var job = new VelocityJob() { deltaTime = Time.deltaTime, position = position, velocity = velocity };

// Schedule a parallel-for job. First parameter is how many for-each iterations to perform. // The second parameter is the batch size, // essentially the no-overhead innerloop that just invokes Execute(i) in a loop. // When there is a lot of work in each iteration then a value of 1 can be sensible. // When there is very little work values of 32 or 64 can make sense. JobHandle jobHandle = job.Schedule(position.Length, 64);

// Ensure the job has completed. // It is not recommended to Complete a job immediately, // since that reduces the chance of having other jobs run in parallel with this one. // You optimally want to schedule a job early in a frame and then wait for it later in the frame. jobHandle.Complete();

Debug.Log(job.position[0]);

// Native arrays must be disposed manually. position.Dispose(); velocity.Dispose(); } }

公共方法

Execute对特定迭代索引执行工作。