Waitgroups in UnrealScript

To wait for multiple tasks to finish, we can use a `Latch` in UnrealScript. This is similar to the concept of a WaitGroup in other languages.

```unrealscript
class WaitGroupExample extends Object;

var int WorkerCount;
var Latch WorkerLatch;

function Init()
{
    WorkerCount = 5;
    WorkerLatch = Spawn(class'Latch');
    WorkerLatch.InitializeCount(WorkerCount);
}

function Worker(int id)
{
    `log("Worker" @ id @ "starting");
    
    // Sleep to simulate an expensive task.
    Sleep(1.0);
    
    `log("Worker" @ id @ "done");
    
    WorkerLatch.CountDown();
}

function StartWorkers()
{
    local int i;
    
    for (i = 1; i <= WorkerCount; i++)
    {
        // Launch several workers and increment the Latch counter for each.
        WorkerLatch.CountUp();
        
        // Start each worker in a separate timer
        SetTimer(0.0, false, 'Worker', self, i);
    }
    
    // Wait for all workers to finish
    WorkerLatch.Await();
    
    `log("All workers finished");
}

defaultproperties
{
}

In this UnrealScript example, we use a Latch to simulate the behavior of a WaitGroup. The Latch is initialized with a count equal to the number of workers we want to run.

The Worker function simulates an expensive task by using Sleep(1.0) to pause execution for 1 second.

In the StartWorkers function, we launch several workers using timers. Each worker is started with a separate timer call, which allows them to run concurrently. The Latch is incremented before starting each worker and decremented when each worker finishes.

After starting all workers, we call WorkerLatch.Await() to block until all workers have finished.

Note that UnrealScript doesn’t have true multithreading, so this example uses timers to simulate concurrent execution. The actual execution of workers may not be truly parallel, but will be interleaved by the game engine.

Also, error handling in UnrealScript is typically done through logging and doesn’t have a direct equivalent to the errgroup package mentioned in the original example. You would need to implement your own error tracking mechanism if required.

To run this example, you would typically include this class in your UnrealScript project and call the StartWorkers function from an appropriate place in your game logic.

The output might look something like this:

Worker 1 starting
Worker 2 starting
Worker 3 starting
Worker 4 starting
Worker 5 starting
Worker 1 done
Worker 3 done
Worker 2 done
Worker 5 done
Worker 4 done
All workers finished

The order of workers starting and finishing may vary between different runs.