Unity / C#
Intermediate
Unity 2021.3+ / Unity 6
Unity C# Job System과 Burst 컴파일러를 활용한 멀티스레드 병렬 연산 기초Multithreaded Parallel Computing Basics with Unity C# Job System and Burst Compiler
메인 스레드 병목을 줄이고 멀티코어 CPU를 활용하여 대량의 파티클 및 유닛 물리 연산을 병렬로 처리하는 IJobParallelFor 및 NativeArray 실무 패턴.Practical patterns using IJobParallelFor and NativeArray to distribute main-thread workloads across multi-core CPUs for large-scale particle and unit calculations.
#Unity #DOTS #JobSystem #Burst #Optimization
핵심 개념전통적인
for 루프는 단일 메인 스레드에서만 실행되어 대량 연산 시 메인 스레드 부하의 원인이 됩니다. C# Job System으로 작업을 쪼개 워커 스레드에 분산시키고, Burst 컴파일러로 C# 코드를 벡터화(SIMD)된 네이티브 머신 코드로 컴파일하면 연산 속도가 크게 향상됩니다.Core ConceptTraditional
for loops execute on a single main thread, becoming a source of main-thread bottlenecks during heavy calculations. Splitting workloads across worker threads with the C# Job System and compiling C# code into vectorized (SIMD) native machine code with the Burst Compiler significantly improves execution speed.1. 병렬 잡(Parallel Job) C# 코드1. Parallel Job C# Implementation
using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;
using Unity.Mathematics;
using UnityEngine;
[BurstCompile]
public struct MovementJob : IJobParallelFor
{
public NativeArray<float3> positions;
[ReadOnly] public NativeArray<float3> velocities;
public float deltaTime;
public void Execute(int index)
{
positions[index] += velocities[index] * deltaTime;
}
}
public class JobRunner : MonoBehaviour
{
private NativeArray<float3> _positions;
private NativeArray<float3> _velocities;
private void Awake()
{
int count = 10000;
_positions = new NativeArray<float3>(count, Allocator.Persistent);
_velocities = new NativeArray<float3>(count, Allocator.Persistent);
}
private void Update()
{
var job = new MovementJob
{
positions = _positions,
velocities = _velocities,
deltaTime = Time.deltaTime
};
// 64개 단위로 청크 분할하여 워커 스레드 스케줄
JobHandle handle = job.Schedule(_positions.Length, 64);
handle.Complete(); // 프레임 동기화
}
private void OnDestroy()
{
if (_positions.IsCreated) _positions.Dispose();
if (_velocities.IsCreated) _velocities.Dispose();
}
}
using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;
using Unity.Mathematics;
using UnityEngine;
[BurstCompile]
public struct MovementJob : IJobParallelFor
{
public NativeArray<float3> positions;
[ReadOnly] public NativeArray<float3> velocities;
public float deltaTime;
public void Execute(int index)
{
positions[index] += velocities[index] * deltaTime;
}
}
public class JobRunner : MonoBehaviour
{
private NativeArray<float3> _positions;
private NativeArray<float3> _velocities;
private void Awake()
{
int count = 10000;
_positions = new NativeArray<float3>(count, Allocator.Persistent);
_velocities = new NativeArray<float3>(count, Allocator.Persistent);
}
private void Update()
{
var job = new MovementJob
{
positions = _positions,
velocities = _velocities,
deltaTime = Time.deltaTime
};
// Split into chunks of 64 and schedule across worker threads
JobHandle handle = job.Schedule(_positions.Length, 64);
handle.Complete(); // Synchronize on the current frame
}
private void OnDestroy()
{
if (_positions.IsCreated) _positions.Dispose();
if (_velocities.IsCreated) _velocities.Dispose();
}
}
2. 실무 적용 및 주의사항2. Practical Considerations
- 네이티브 컨테이너 명시적 해제:
NativeArray는 C# 가비지 컬렉터가 관리하지 않는 비관리(Unmanaged) 메모리를 사용하므로, 사용이 끝난 시점이나OnDestroy()에서 반드시Dispose()를 호출하여 메모리 누수를 방지해야 합니다. - 참조 타입 및 메인 스레드 API 제한: Burst로 컴파일되는 Job 구조체 내부에서는 일반 C# 클래스(참조 타입)를 포함하거나
Transform등 메인 스레드 전용 Unity API에 접근할 수 없으며,float3같은 값 타입(Blittable Type)만 사용해야 합니다. - 스케줄링과 완료 시점 분리:
Schedule()호출 직후 같은 자리에서Complete()를 호출하면 메인 스레드가 즉시 대기 상태에 들어갑니다.Update()에서 스케줄링하고LateUpdate()에서Complete()를 호출하면 워커 스레드의 병렬 실행 시간을 확보할 수 있습니다.
- Explicitly Dispose Native Containers:
NativeArrayallocates unmanaged memory outside the C# garbage collector, so you must callDispose()when finished or insideOnDestroy()to prevent memory leaks. - No Reference Types or Main-Thread APIs: Burst-compiled Job structs cannot contain managed C# classes (reference types) or access main-thread Unity APIs such as
Transform; only blittable value types likefloat3are allowed. - Separate Schedule and Complete Calls: Calling
Complete()immediately afterSchedule()forces the main thread to wait right away. Scheduling jobs inUpdate()and callingComplete()inLateUpdate()gives worker threads time to execute in parallel.
Job System과 Burst 컴파일러를 결합하면 대규모 유닛 이동이나 탄막 판정처럼 CPU 연산이 집중되는 작업을 워커 스레드로 분산하여 메인 스레드 프레임을 안정적으로 유지할 수 있습니다.
Combining the Job System and Burst Compiler offloads CPU-intensive tasks such as crowd movement and projectile checks to worker threads, keeping main-thread frame times stable.