This post originated from an RSS feed registered with Java Buzz
by Paul Brown.
Original Post: A Little Fun with Concurrency in Io
Feed Title: mult.ifario.us
Feed URL: http://feeds.feedburner.com/MultifariousCategoryJava
Feed Description: Software. Business. Java. XML. Web Services.
I've been experimenting with Io, a "small, prototype-based programming language". Io has a host of interesting features, but the way it deals with concurrency is what interests me. (See, e.g., 2004-02-16 or 2004-01-04.)Io supports both an interactive front-end and an executable mode; what follows is a session with the front-end that illustrates some of the concurrency features. This first set of code creates an object and adds a method named weave that iterates through an input string character by character, yielding control after each iteration. The trio of gibberish strings will be used later:Io> o1 := Object clone
Io> o1 weave := method(str, str foreach(i,v,v asCharacter print; yield))
Io> s1 := "hlccrtod"; s2 := "eooue r"; s3 := "l nrnwl";
Io> chug := block(while(activeCoroCount > 1, yield))The chug code block is only necessary because the interactive front-end grabs control after the first call to yield; it could be left out in a standalone Io program.The first line below invokes the weave method three times, synchronously; the second line makes three asynchronous calls on the weave method (on the same object). (The @@ decoration on the method means call asynchronously and return Nil.)Io> o1 weave(s1); o1 weave(s2); o1 weave(s3);
hlccrtodeooue rl nrnwl
Io> o1 @@weave(s1); o1 @@weave(s2); o1 @@weave(s3); chug
hlccrtodeooue rl nrnwlBoth produce the same output because Io handles messages in FIFO order.Objects in Io are like threads, and if we clone the object o1 and make three asynchronous calls, the three strings are interleaved character-by-character:Io> o2 := o1 clone; o3 := o1 clone
Io> o1 @@weave(s1); o2 @@weave(s2); o3 @@weave(s3); chug
hello concurrent worldIo also supports Futures, i.e., handles to the to-be-returned value of an asynchronously invoked method.Io> bar := Object clone
Io> bar l8r := method(str, yield; str)
Io> bar l8r("hello from the present")
==> "hello from the present"
Io> foochur := bar @l8r("hello from the past")
==> Future_0x3279d0A Nil return value from isReady means that the method hasn't completed (and that's what's expected from the initial yield in the l8r method):Io> foochur isReady
==> NilDislodging it with a call to the chug block defined above makes the result accessible:Io> chug
Io> foochur isReady
==> Future_0x3279d0
Io> foochur value
==> "hello from the past"Io also allows methods to be attached to futures as listeners via sendResultTo:Io> echo := Object clone; echo out := method(str, str print)
Io> bar @(l8r("hello")) sendResultTo(echo,"out")
==> Future_0x32e210
Io> chug
hello