Worker Pools in AngelScript
Our example demonstrates how to implement a worker pool using threads and queues in AngelScript.
#include <angelscript.h>
#include <scriptarray/scriptarray.h>
#include <scriptdictionary/scriptdictionary.h>
#include <chrono>
#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>
// Worker function that processes jobs
void worker(int id, CScriptArray@ jobs, CScriptArray@ results)
{
while (true)
{
int job;
{
// Acquire the job from the queue
lock_guard<mutex> lock(jobsMutex);
if (jobs.GetSize() == 0)
break;
job = jobs[jobs.GetSize() - 1];
jobs.RemoveAt(jobs.GetSize() - 1);
}
Print("worker " + id + " started job " + job + "\n");
this_thread::sleep_for(chrono::seconds(1));
Print("worker " + id + " finished job " + job + "\n");
{
// Add the result to the results array
lock_guard<mutex> lock(resultsMutex);
results.InsertLast(job * 2);
}
}
}
void main()
{
// Create job and result arrays
const int numJobs = 5;
array<int> jobs(numJobs);
array<int> results;
// Initialize jobs
for (int j = 1; j <= numJobs; j++)
jobs.insertLast(j);
// Create worker threads
array<thread> workers;
for (int w = 1; w <= 3; w++)
workers.insertLast(thread(@worker, w, @jobs, @results));
// Wait for all workers to finish
for (uint i = 0; i < workers.length(); i++)
workers[i].join();
// Print results
Print("Results: ");
for (uint i = 0; i < results.length(); i++)
Print(results[i] + " ");
Print("\n");
}
In this AngelScript version, we use threads to simulate goroutines and a shared array to simulate channels. The worker
function processes jobs from the jobs
array and adds results to the results
array. We use mutexes to ensure thread-safe access to these shared resources.
The main
function sets up the job queue, creates worker threads, and waits for them to complete. Finally, it prints the results.
To run the program:
$ angelscript worker-pools.as
worker 1 started job 5
worker 2 started job 4
worker 3 started job 3
worker 1 finished job 5
worker 1 started job 2
worker 2 finished job 4
worker 3 finished job 3
worker 2 started job 1
worker 3 finished job 3
worker 1 finished job 2
worker 2 finished job 1
Results: 2 4 6 8 10
This example demonstrates how to implement a worker pool pattern in AngelScript. The program creates three worker threads that process five jobs concurrently. Despite doing about 5 seconds of total work, the program finishes in about 2 seconds due to the parallel execution of the workers.
Note that AngelScript doesn’t have built-in concurrency primitives like Go’s goroutines and channels. Instead, we use C++ standard library features like std::thread
, std::mutex
, and std::condition_variable
which are assumed to be bound to the AngelScript environment. The exact implementation may vary depending on how these features are exposed to AngelScript in your specific setup.