Logo

Programming-Idioms

  • JS
  • D

Idiom #25 Send a value to another thread

Share the string value "Alan" with an existing running process which will then display "Hello, Alan"

import std.concurrency;
import std.stdio;
auto t = spawn( {
   receive( (string s) { writefln("Hello, %s", s); } );
} );

t.send("Alan");

receive takes as parameters lambda functions (or delegates) to handle each type that may be received.
import { isMainThread, Worker, parentPort } from 'worker_threads';
if (isMainThread) {
  const worker = new Worker(new URL(import.meta.url));
  worker.postMessage('Alan');
} else {
  parentPort.once('message', (message) => {
    console.log(`Hello, ${message}`);
  });
}

Only supported in Node.js
{
  // in file worker.js
  onmessage = ({data}) => {
    console.log (`Hello, ${data}`)
  }
}
{
  // in file main.js
  const worker = new Worker ('worker.js')
  worker.postMessage ('Alan')
}

Not supported in Internet Explorer or NodeJS.
declare

   task Greeter is
      entry Greet (Name : String);
   end Greeter;

   task body Greeter is
   begin

      accept Greet (Name : String) do
         Ada.Text_IO.Put_Line ("Hello, " & Name);
      end Greet;

   end Greeter;

begin
   Greeter.Greet ("Alan");
end;

This is called a rendez-vous in Ada. The caller is blocked until the Greet accept statement is completed.

New implementation...
< >
programming-idioms.org