Logo

Programming-Idioms

  • JS
  • Elixir
  • C#

Idiom #25 Send a value to another thread

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

using System.Threading;
using(var readyEvent = new ManualResetEvent(false))
{
    var thread = new Thread(() =>
    {
        readyEvent.WaitOne();
        Console.WriteLine(value);
    });

    thread.Start();

    value = "Alan";
    readyEvent.Set();

    thread.Join();
}
using System.Collections.Concurrent;
using System.Threading;
ConcurrentQueue<int> coll = new ConcurrentQueue<int>();
var ts = new CancellationTokenSource();
CancellationToken ct = ts.Token;

Task t2 = Task.Factory.StartNew(() => {
	while (true) {
		Thread.Sleep(250);
		if (ct.IsCancellationRequested) break;
			bool isDequeued = coll.TryDequeue(out int result);
			if (isDequeued) Console.WriteLine(result);
	}});
while (true) {
	int val = Convert.ToInt32(Console.ReadLine());
	if (val == -1) break;
	coll.Enqueue(val);
}
ts.Cancel();

This example uses a Task (not strictly a Thread) to print integers passed to it. It ends when a -1 is entered.
{
  // 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.
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
pid = spawn fn ->
  receive do
    {:hello, name} ->
      IO.puts("Hello, #{name}")
    _ ->
      IO.puts(:stderr, "Unexpected message received")
  end
end

send pid, {:hello, "Alan"}

We spawn a process and store its PID in pid, then we send the message {:hello, "Alan"} to the PID. In the code for that process, we try to receive a message, destructuring it into the name, which we then print.
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