TOOLS GAMES DEVLOG DOCS ABOUT CONTACT
HOME > DOCS > Unity / C# > Unity C# Job System과 Burst 컴파일러를 활용한 멀티스레드 병렬 연산 기초
Unity / C# Intermediate Unity 2021.3+ / Unity 6

Unity C# Job System과 Burst 컴파일러를 활용한 멀티스레드 병렬 연산 기초

메인 스레드 병목을 없애고 CPU 모든 코어를 활용하여 수만 개의 파티클/적 유닛 물리 연산을 0.5ms 내에 마치는 IJobParallelFor 및 NativeArray 실무 패턴.

#Unity #DOTS #JobSystem #Burst #Optimization
핵심 개념전통적인 for 루프는 단일 메인 스레드에서만 돌아 프레임 드랍의 주범이 됩니다. C# Job System으로 작업을 쪼개 워커 스레드에 분산시키고, Burst 컴파일러로 C# 코드를 고도로 벡터화(SIMD)된 네이티브 머신 코드로 컴파일하면 연산 속도가 최대 20~50배 향상됩니다.

1. 병렬 잡(Parallel Job) C# 코드

MovementJob.cs
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();
    }
}

참고자료 & 관련 링크