EveryDay.DevUp

[Unity] Job 시스템 이해, IJobParallelFor- (4) 본문

DotsTween

[Unity] Job 시스템 이해, IJobParallelFor- (4)

EveryDay.DevUp 2020. 7. 15. 22:46

※ JobHandle을 보기 전, Job 시스템의 이해가 필요하다면 하단의 게시물을 참고

https://everyday-devup.tistory.com/97

 

[Unity] Job 시스템 이해, IJob - (1)

● Unity의 Job 시스템에 대한 이해가 필요하다면, 다음의 게시물을 참고 https://everyday-devup.tistory.com/69 [Unity] DOTS - 프로세스, 스레드, C# Job 시스템 ECS를 알아보기 전 DOTS에 대해 궁금한 점이..

everyday-devup.tistory.com

● Interface IJobParallelFor

▶ IJob이 단일 워커 스레드에서 Execute()가 한번 처리되었다면, IJobParallerFor는 사용 가능한 모든 워커 스레드에서 Execute()가 실행 횟수 만큼 나뉘어서 실행된다.

▶ IJobParallelFor는 Execute()의 로직은 동일하지만 특정 Index의 매개 변수가 다를 때 사용하면 유용하다. 같은 로직을 여러번 수행할 때 묶음으로 처리함으로써 성능 향상의 도움이 된다.

[JobProducerType( typeof( IJobParallelForExtensions.ParallelForJobStruct<> ) )]
public interface IJobParallelFor
{
	//
	// 요약:
	//     Implement this method to perform work against a specific iteration index.
	//
	// 매개 변수:
	//   index:
	//     The index of the Parallel for loop at which to perform work.
	void Execute(int index);
}

▶ IJob과 달리 Execute에 Index가 추가되었는데, 해당 Index로 Job의 데이터 리스트에서 가져올 데이터를 확인할 수 있다.

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

public class JobSample : MonoBehaviour
{
	/// <summary>
	/// Excute의 Index를 result 배열에 넣어주는 단순한 예제
	/// </summary>
	struct JobParallel : IJobParallelFor
	{
		public NativeArray<int> result;

		public void Execute(int index)
		{
			result[index] = index;
		}
	}

	// Job을 실행할 횟수
	int count = 10000;
	// 하나의 워커 스레드당 설정할 Job의 개수
	// 워커스레드가 3개인 경우 10000개의 Job을 10개씩 나누어 3개의 워커 스레드에 나눈다. 
	// 10000/10 = 1000, 1000/3 = 333 개 묶음으로 나뉨
	int batchCount = 10;

	void Start()
	{
		NativeArray<int> result = new NativeArray<int>( count, Allocator.TempJob );

		JobParallel jobParallel = new JobParallel();
		jobParallel.result = result;

		// count, batchCount에 따라 워커 스레드에 Job이 나뉘게 된다.
		JobHandle handle = jobParallel.Schedule( count, batchCount );

		handle.Complete();
		result.Dispose();
	}
}

▶ IJob이 한번에 여러개의 워커 스레드에서 실행된다는 것 외에는 기본적인 개념은 IJob과 동일하다.

IJobParallelFor를 확장하여, 한번에 여러개의 Transform을 처리하는 Job을 만들 수 있는 IJobParallelForTransform도 있다. IJobParallelForTransform를 사용하려면 using UnityEngine.Jobs 을 선언해야한다.

▶ PackageManager에서 Jobs Preview Package를 Import하면 IJobParallelFor의 확장형 인터페이스를 추가로 사용할 수 있다.

: PreviewPackage이기 때문에 해당 확장형 인터페이스를 사용하기 보다는 기존의 IJobParallelFor를 사용하는 것이 현재로써는 더 좋다.

 참고 자료

https://docs.unity3d.com/kr/current/Manual/JobSystem.html