Channel Synchronization in UnrealScript

Our example demonstrates how to synchronize execution across different threads in UnrealScript. We’ll use a custom event to simulate the synchronization behavior.

class ChannelSynchronization extends Object;

var bool bWorkerDone;

function Worker()
{
    `Log("working...");
    Sleep(1.0);
    `Log("done");
    
    bWorkerDone = true;
}

function Init()
{
    bWorkerDone = false;
    
    // Start the worker function in a separate thread
    SetTimer(0.0, false, 'Worker');
    
    // Wait until the worker is done
    while (!bWorkerDone)
    {
        Sleep(0.1);
    }
    
    `Log("Main thread finished");
}

defaultproperties
{
}

In this UnrealScript example:

  1. We define a Worker function that simulates some work by logging messages and using Sleep to pause execution.

  2. The Init function serves as our entry point, similar to the main function in other languages.

  3. We use a boolean variable bWorkerDone to indicate when the worker has finished its task.

  4. The SetTimer function is used to start the Worker function in a separate thread.

  5. We use a while loop in the main thread to wait until the worker is done. This simulates the blocking receive in the original example.

To run this code, you would typically place it in a script file (e.g., ChannelSynchronization.uc) within your UnrealScript project. The Unreal Engine would then compile and execute it as part of the game or editor process.

Note that UnrealScript doesn’t have built-in channels or goroutines like some other languages. Instead, we use UnrealScript’s timer system and a boolean flag to achieve a similar synchronization effect.

If you removed the while loop from this program, the main thread would finish before the worker had a chance to complete its task.