c# job system 和 Unity’s native job system 交互,限制线程数量避免线程资源竞争
好处
提高帧率
省电
NativeContainer
简述
共享内存,用来解决数据是副本的问题
可以让job和主线程访问同一段内存数据
类型
NativeArray
ECS拓展的类型
NativeList
NativeHashMap
NativeMultiHashMap
NativeQueue
NativeContainer and the safety system
DisposeSentinel:处理内存释放问题
AtomicSafetyHandle:处理内存写入竞争问题
多个job并行写入同一个NativeContainer时
job和主线程写入同一个NativeContainer时
同时读取的job不会导致异常
可以通过job依赖配置解决读写竞争问题
可以同时读写的job会降价性能
如果是只读的job就只配置读取能力
静态数据的访问不受安全系统保护
配置进读取的方法
[ReadOnly]
public NativeArray<int> input;
NativeContainer Allocator
使用不同的Allocator是为了在不同的使用情景下获得最好的性能
类型
Temp,最快,适用于 <=1 帧的时间内,并且一定要在方法返回前释放,不可以传给Jobs
TempJob,比Temp慢,适用于 <=4 帧的时间内,大部分小型job使用
Persistent,最慢,整个应用的生命周期时间都可以用,性能敏感的地方避免使用这种类型
Creating jobs
步骤
创建struct : IJob
增加成员变量
创建Execute方法
在一个cup上运行1次
注意点
通过在job中通过NativeContainer方法主线程的数据
// Job adding two floating point values together
public struct MyJob : IJob
{
public float a;
public float b;
public NativeArray<float> result;
public void Execute()
{
result[0] = a + b;
}
}
Scheduling jobs
步骤
创建job
准备数据
调用Schedule
注意
一旦调用Schedule,job就会被加入job队列。不能打断一个job
Schedule只能在主线程调用
示例
// Create a native array of a single float to store the result. This example waits for the job to complete for illustration purposes
NativeArray<float> result = new NativeArray<float>(1, Allocator.TempJob);
// Set up the job data
MyJob jobData = new MyJob();
jobData.a = 10;
jobData.b = 10;
jobData.result = result;
// Schedule the job
JobHandle handle = jobData.Schedule();
// Wait for the job to complete
handle.Complete();
// All copies of the NativeArray point to the same memory, you can access the result in "your" copy of the NativeArray
float aPlusB = result[0];
// Free the memory allocated by the result array
result.Dispose();