페이지

2021년 3월 3일 수요일

Unity C# Job System 5

 ParallelFor jobs

IJob 들은 코어당 하나의 Job (Execute )을 수행한다. 그에 반해 IJobParallelFor 은 하나의 코어에 여러개의 Job들을 수행할수 있다. 

Note: ParallelFor Job은 IJobParallelFor 인터페이스를 구현한 structure이다. 



struct IncrementByDeltaTimeJob: IJobParallelFor {

    public NativeArray<float> values;
    public float deltaTime;

    public void Execute(int index){
        float temp = values[index];
        temp += deltaTime;
        values[index] = temp;
    }
}


Scheduling ParallelFor Jobs

이를 사용할때는 NativeArray 데이타 길이를 정해야 한다.  코어는 한정적이고 처리해야할  IJobParallelFor의 Execute들이 많다.이럴때는 몇개의 Job들을 묶어서 하나의 Batch 로 만든다. 이들 여러개의 Batch들을 Job Queue에 넣고 NativeJob 을 생성한다. Native Job System은 각 core당 NativeJob Queue로부터 NativeJob들을 꺼내와서 Batch들을 수행한다.



만약 다른 NativeJob들 보다 먼저 batch수행을 끝낸것 이 있다면, 그것은 현재 남아 있는 다른 NativeJob의 batch들을 가져와서 처리한다. 한번에 남아있는 batch들의 반정도 양만 가져온다. 
이를 최적화 하기위해서, batch count를 시스템에 맞게 적절히 조절할 필요가 있다. Batch count가 너무 낮으면,  core에 비해 처리해야할 Queue 가 많아지며, Batch count가 너무 높으면 한 core에서 수행할 작업자 스레드의 양이 증가한다. 

An example of scheduling a ParallelFor job

// Job adding two floating point values together
public struct MyParallelJob: IJobParallelFor {
    [ReadOnly]
    public NativeArray<float> a;
    [ReadOnly]
    public NativeArray<float> b;
    public NativeArray<float> result;

    public void Execute(int i ){
        result[i] = a[i] + b[i];
    }
}


// Main Thread

NativeArray<float> a = new NativeArray<float>(2, Allocator.TempJob);
NativeArray<float> b = new NativeArray<float>(2, Allocator.TempJob);
NativeArray<float> result = new NativeArray<float>(2, Allocator.TempJob);

a[0] = 1.1;
b[0] = 2.2;
a[1] = 3.3;
b[1] = 4.4;

MyParallelJob jobData = new MyParallelJob();
jobData.a = a;
jobData.b = b;
jobData.result = result;

// Schedule the job with one Execute per index in the results array and only 1 item per processing batch
JobHandle handle = jobData.Schedule(result.Length, 1);

// Wait for the job to complete
handle.Complete();

// Free the memory allocated by the arrays
a.Dispose();
b.Dispose();
result.Dispose();

ParallelForTransform jobs

ParallelFor job의 또 다른 타입. 이는 GameObject의 Transform만을 다루기 위해 나왔다.


댓글 없음:

댓글 쓰기