Concurrent computing

From Rosetta Code
Revision as of 02:36, 8 February 2007 by rosettacode>Waldorf
Task
Concurrent computing
You are encouraged to solve this task according to the task description, using any language you may know.

Using either native language concurrency syntax or freely available libraries write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order. Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.


Ada

with Ada.Text_Io; use Ada.Text_Io;
with Ada.Numerics.Float_Random; use Ada.Numerics.Float_Random;
with Ada.strings.Unbounded; use Ada.Strings.Unbounded;

procedure Concurrent_Hello is
   Seed : Generator;
   
   task type Writer is 
      entry Start(Message : String);
   end Writer;
   
   task body Writer is
      Sleep_Time : Float;
      Words : Unbounded_String;
   begin
      accept Start(Message : String) do
         Words := To_Unbounded_String(Message);
      end Start;
      Sleep_Time := Random(Seed);
      delay Duration(Sleep_Time);
      Put_Line(To_String(Words));
   end Writer;
   T1 : Writer;
   T2 : Writer;
   T3 : Writer;
begin
   Reset(Seed);
   delay 0.001;
   T1.Start("Enjoy");
   T2.Start("Rosetta");
   T3.Start("Code");
end Concurrent_Hello;

JavaScript

Interpreter: Firefox 2.0

var textbox = document.getElementsByTagName("textarea")[0];
setTimeout( function(){ textbox.value += "Enjoy\n";   }, Math.random() * 1000 );
setTimeout( function(){ textbox.value += "Rosetta\n"; }, Math.random() * 1000 );
setTimeout( function(){ textbox.value += "Code\n";    }, Math.random() * 1000 );

Tcl

Assuming that "random" means that we really want the words to appear in random (rather then "undefined" or "arbitrary") order:

 after [expr int(1000*rand())] {puts "Enjoy"}
 after [expr int(1000*rand())] {puts "Rosetta"}
 after [expr int(1000*rand())] {puts "Code"}

will execute each line after a randomly chosen number (0...1000) of milliseconds.

A step towards "undefined" would be to use after idle, which is Tcl for "do this whenever you get around to it". Thus:

 after idle {puts "Enjoy"}
 after idle {puts "Rosetta"}
 after idle {puts "Code"}

(While no particular order is guaranteed by the Tcl spec, the currently existing interpreters would probably all execute these in the order in which they were added to the after queue).