페이지

2021년 2월 25일 목요일

Unity C# Job System 3

 Creating Jobs

  • Job을 만들기 위해서는 IJob 인터페이스를 구현한다
  • 해당 Job 사용할 멤버변수들을 추가한다
  • Execute 함수를 Job내에 구현한다.

Jobs이 수행되면, Execute 함수는 하나의 코어에 한번 실행된다.

Note :  Job을 설계할때, NativeContainer가 아닌것 data들은 복사본이라는 것을 기억해야 한다. 그래서 메인스레드에서 data를 접근하는 유일한 방법은 NativeContainer를 사용하는 것 밖에 없다.

public struct MyJob:IJob {
    public float a;
    public float b;
    public NativeArray<float> result;
    public void Execute(){
        result[0] = a + b;
    }
}


Scheduling Jobs

메인스레드에서 Job을 스케줄하기 위해서는
  • Instantiate the job
  • Populate the Job's data
  • Call the Schedule method
Schedule함수를 호출하는 것은 해당 Job을 Job Queued에 넣는 다는 것을 의미한다. 그러면 시스템은 적절한 시간에 그 Job을 수행한다. 한번 Schedule 되었으면, 너는 그것을 방해할수 없다.
단지, 메인스레드에서 Schedule 함수만 호출할수 있다.


NativeArray<float> result = new NativeArray<float>(1, Allocator.TempJob);

MyJob jobData = new MyJob();
jobData.a = 10;
jobData.b = 10;
jobData.result = result;

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();

댓글 없음:

댓글 쓰기