Worker Pools in UnrealScript

class WorkerPool extends Object;

struct WorkerJob
{
    var int JobID;
};

struct WorkerResult
{
    var int ResultValue;
};

var array<WorkerJob> Jobs;
var array<WorkerResult> Results;
var int NumJobs;
var int NumWorkers;

function Init()
{
    NumJobs = 5;
    NumWorkers = 3;
}

function Worker(int WorkerID)
{
    local WorkerJob Job;
    local WorkerResult Result;

    while (Jobs.Length > 0)
    {
        Job = Jobs[0];
        Jobs.Remove(0, 1);

        `log("Worker" @ WorkerID @ "started job" @ Job.JobID);
        Sleep(1.0);
        `log("Worker" @ WorkerID @ "finished job" @ Job.JobID);

        Result.ResultValue = Job.JobID * 2;
        Results.AddItem(Result);
    }
}

function RunWorkerPool()
{
    local int i;

    // Create jobs
    for (i = 1; i <= NumJobs; i++)
    {
        Jobs.AddItem((JobID: i));
    }

    // Start workers
    for (i = 1; i <= NumWorkers; i++)
    {
        SetTimer(0.0, false, 'Worker', self);
    }

    // Wait for all jobs to complete
    while (Results.Length < NumJobs)
    {
        Sleep(0.1);
    }

    // Print results
    for (i = 0; i < Results.Length; i++)
    {
        `log("Result:" @ Results[i].ResultValue);
    }
}

defaultproperties
{
}

In this example, we’ll look at how to implement a worker pool using UnrealScript’s timer system and arrays.

Here’s the Worker function, which simulates processing jobs. It receives work from the Jobs array and sends the corresponding results to the Results array. We’ll use a sleep function to simulate an expensive task.

The RunWorkerPool function sets up our pool of workers:

  1. We create 5 jobs and add them to the Jobs array.
  2. We start 3 workers using UnrealScript’s timer system, which allows for concurrent execution.
  3. We wait for all jobs to complete by checking the Results array length.
  4. Finally, we print all the results.

To use this worker pool:

class MyGame extends GameInfo;

function StartMatch()
{
    local WorkerPool Pool;

    Pool = new class'WorkerPool';
    Pool.Init();
    Pool.RunWorkerPool();
}

When we run this program, it will show the 5 jobs being executed by various workers. The program will take about 2 seconds to complete despite doing about 5 seconds of total work because there are 3 workers operating concurrently.

Note that UnrealScript doesn’t have built-in concurrency primitives like channels or goroutines, so we’ve simulated concurrent behavior using UnrealScript’s timer system and arrays. This implementation might not be as efficient as true concurrent execution, but it demonstrates the concept of a worker pool in UnrealScript.