Waitgroups in AngelScript
Our example demonstrates how to wait for multiple tasks to finish using a concept similar to wait groups. In AngelScript, we’ll use a custom WaitGroup
class to simulate this behavior.
#include <angelscript.h>
#include <scriptarray/scriptarray.h>
#include <scriptdictionary/scriptdictionary.h>
#include <chrono>
#include <thread>
#include <iostream>
// Custom WaitGroup class to simulate Go's sync.WaitGroup
class WaitGroup {
private int counter = 0;
void Add(int delta) {
counter += delta;
}
void Done() {
counter--;
}
void Wait() {
while (counter > 0) {
// Busy wait (not ideal, but simulates the concept)
}
}
}
// This is the function we'll run in every task
void worker(int id) {
print("Worker " + id + " starting\n");
// Sleep to simulate an expensive task
sleep(1000); // Sleep for 1 second
print("Worker " + id + " done\n");
}
void main() {
// This WaitGroup is used to wait for all the
// tasks launched here to finish
WaitGroup@ wg = WaitGroup();
// Launch several tasks and increment the WaitGroup
// counter for each
for (int i = 1; i <= 5; i++) {
wg.Add(1);
// Wrap the worker call in a function that makes sure to tell
// the WaitGroup that this worker is done
thread_create(function() {
worker(i);
wg.Done();
});
}
// Block until the WaitGroup counter goes back to 0;
// all the workers notified they're done
wg.Wait();
}
To run this program, you would need to set up an AngelScript environment with the necessary modules and bindings. The exact setup may vary depending on your specific AngelScript implementation.
When executed, the output might look something like this:
Worker 3 starting
Worker 1 starting
Worker 2 starting
Worker 4 starting
Worker 5 starting
Worker 2 done
Worker 1 done
Worker 3 done
Worker 5 done
Worker 4 done
Note that the order of workers starting up and finishing is likely to be different for each invocation.
This example demonstrates concurrent execution in AngelScript, simulating the behavior of Go’s WaitGroups. However, it’s important to note that AngelScript’s concurrency model may differ from Go’s, and the exact implementation of threading and synchronization can vary based on the host application.
AngelScript doesn’t have built-in concurrency primitives like Go, so we’ve used a custom WaitGroup
class and the thread_create
function (which would need to be implemented by the host application) to simulate similar behavior. The sleep
function is also assumed to be provided by the host application.
Remember that error handling in this approach may need to be implemented separately, as we don’t have a direct equivalent to Go’s errgroup
package in AngelScript.