Goroutines in ActionScript

Our example demonstrates how to use goroutines, which are lightweight threads of execution. Here’s the translation into ActionScript.

package {
    import flash.utils.setTimeout;
    import flash.display.Sprite;
    
    public class GoroutineExample extends Sprite {
        public function GoroutineExample() {
            // Call function directly, running it synchronously
            f("direct");
            
            // Call function in a "goroutine" (setTimeout is used to simulate asynchronous execution)
            setTimeout(function():void { f("goroutine"); }, 0);
            
            // Anonymous function call in a goroutine
            setTimeout(function():void { trace("going"); }, 0);
            
            // Wait for "goroutines" to finish
            setTimeout(function():void { trace("done"); }, 1000);
        }
        
        private function f(from:String):void {
            for (var i:int = 0; i < 3; i++) {
                trace(from + " : " + i);
            }
        }
    }
}

To run this ActionScript program, you will need an environment that supports ActionScript, such as Adobe Animate or an ActionScript compiler. Place the code in a .as file and run it.

When we run this program, we see the output of the blocking call first, then the output of the two goroutines. The goroutines’ output may be interleaved, because setTimeout functions are being run concurrently by the ActionScript runtime.

> direct : 0
> direct : 1
> direct : 2
> goroutine : 0
> going
> goroutine : 1
> goroutine : 2
> done

Next, we’ll look at a complement to goroutines in concurrent programs: channels.