Waitgroups in ActionScript

ActionScript doesn’t have built-in support for multithreading or concurrent execution like Go’s goroutines. However, we can simulate a similar behavior using timers and event-driven programming. Here’s an example that demonstrates a concept similar to WaitGroups:

package {
    import flash.display.Sprite;
    import flash.utils.setTimeout;
    import flash.events.Event;

    public class WaitGroupExample extends Sprite {
        private var workersCompleted:int = 0;
        private const TOTAL_WORKERS:int = 5;

        public function WaitGroupExample() {
            for (var i:int = 1; i <= TOTAL_WORKERS; i++) {
                startWorker(i);
            }
        }

        private function startWorker(id:int):void {
            trace("Worker " + id + " starting");
            
            // Simulate an expensive task with setTimeout
            setTimeout(function():void {
                trace("Worker " + id + " done");
                workerDone();
            }, 1000);
        }

        private function workerDone():void {
            workersCompleted++;
            if (workersCompleted == TOTAL_WORKERS) {
                allWorkersCompleted();
            }
        }

        private function allWorkersCompleted():void {
            trace("All workers completed");
        }
    }
}

This ActionScript code demonstrates a concept similar to WaitGroups. Here’s how it works:

  1. We define a WaitGroupExample class that extends Sprite, which is a basic display object in ActionScript.

  2. The workersCompleted variable keeps track of how many workers have finished their tasks, similar to the counter in a WaitGroup.

  3. In the constructor, we start five workers using a loop, similar to launching goroutines in the Go example.

  4. The startWorker function simulates an expensive task using setTimeout. This is analogous to the time.Sleep in the Go example.

  5. When each worker completes, it calls the workerDone function, which increments the workersCompleted counter.

  6. Once all workers have completed (when workersCompleted equals TOTAL_WORKERS), we call allWorkersCompleted, which is similar to the functionality after wg.Wait() in the Go example.

To run this ActionScript code, you would typically compile it into a SWF file and run it in a Flash Player or AIR runtime environment. The output would be similar to:

Worker 1 starting
Worker 2 starting
Worker 3 starting
Worker 4 starting
Worker 5 starting
Worker 1 done
Worker 2 done
Worker 3 done
Worker 4 done
Worker 5 done
All workers completed

Note that in ActionScript, we don’t have true concurrent execution. The workers are simulated using asynchronous callbacks, which run on the same thread. This approach doesn’t provide true parallelism but can be used to manage multiple asynchronous tasks in a way that’s conceptually similar to WaitGroups in Go.