Search code examples
concurrencyworkerballerina

How to Create Workers Dynamically in Ballerina


How can I create workers dynamically and then wait for them to complete? The number of workers to create is determined at runtime.


Solution

  • You cannot dynamically create workers. But by using async calls, the functionality can be achieved. Check this example:

    function doSomething() returns int {
        return 1;
    }
    
    public function main() {
        future<int>[] results = [];
        int workerLimit = 10;
        foreach int i in 0 ..< workerLimit {
            future<int> asyncResult = start doSomething();
            results.push(asyncResult);
        }
    
        foreach int i in 0 ..< workerLimit {
            int result = check wait results[I];
            // process result
        }
    }