Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #25 Send a value to another thread

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

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;
(require '[clojure.core.async :refer :all])
(def c (chan 1))

(go (println "Hello," (<! c)))

(>!! c "Alan")
#include <future>
#include <mutex>
#include <iostream>
#include <optional>
#include <condition_variable>
//declaration
auto mutex = std::mutex{};
auto cv = std::condition_variable{};
auto variable = std::optional<std::string>{};
auto future = std::async([&]() {
	auto lock = std::unique_lock{mutex, std::defer_lock};
	cv.wait(lock, [&variable](){ return variable.has_value(); });
	std::cout << "Hello, " << *variable << "!" << std::endl;
});

//passing value in main thread (or it can be done in others as well)
{
	auto lock = std::unique_lock{mutex};
	variable = "Alan";
	cv.notify_all();
}
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();
import std.concurrency;
import std.stdio;
auto t = spawn( {
   receive( (string s) { writefln("Hello, %s", s); } );
} );

t.send("Alan");
import "dart:isolate";
sendPort.send("value");
pid = spawn fn ->
  receive do
    {:hello, name} ->
      IO.puts("Hello, #{name}")
    _ ->
      IO.puts(:stderr, "Unexpected message received")
  end
end

send pid, {:hello, "Alan"}
str[1] = "Alan"
sync all
if (this_image() == 1) then
  print *,"Hello, ", str
end if
import "fmt"
go func() {
	v := <-ch
	fmt.Printf("Hello, %v\n", v)
}()

ch <- "Alan"
import Control.Concurrent.Chan
peopleToGreet <- newChan
writeChan peopleToGreet "Alan"
{
  // in file worker.js
  onmessage = ({data}) => {
    console.log (`Hello, ${data}`)
  }
}
{
  // in file main.js
  const worker = new Worker ('worker.js')
  worker.postMessage ('Alan')
}
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}`);
  });
}
https://gist.github.com/f7c174c53efaba4d8575
extension=pthreads.so
class AsyncOperation extends Thread
{
    private $name;

    public function __construct($arg)
    {
        $this->name = $arg;
    }

    public function run()
    {
        sleep(1);
        if ($this->name) {
            printf("Hello %s\n", $this->name);
        }
    }
}

$thread = new AsyncOperation("World");

if ($thread->start()) {
    $thread->merge(['name' => 'Alan']);
}
Uses IdThreadSafe; // From Indy
var Queue: TIdThreadSafeStringList;

type

TTask = class(TThread)
  procedure Execute; override;
end;

procedure TTask.Execute;
begin
  while not Terminated do begin
    Sleep(10);
    with Queue.Lock do try
      while Count > 0 do begin
        WriteLn('Hello, ', Strings[0]);
        Delete(0);
      end;
    finally
      Queue.Unlock;
    end;
  end;
end;

begin
  Queue := TIdThreadSafeStringList.Create;
  TTask.Create(False);
  Queue.Add('Alan');
  Sleep(5000);
end. 
use threads;
use threads::shared;
my @queue :shared;

threads->create('my_task');
push @queue, 'Alan';
sleep 5;

sub my_task {
   while (1) {
      while (@queue) {
         print "Hello, ", (pop @queue), "\n";
      }
      sleep 1;
}

         
      
from queue import Queue
from threading import Thread
q = Queue()

def worker():
    while True:
        print(f"Hello, {q.get()}")
        q.task_done()

Thread(target=worker, daemon=True).start()

q.put("Alan")
q.join()
queue = Queue.new
thread = Thread.new do
  puts queue.pop
end
queue << "Alan"
thread.join
use std::thread;
use std::sync::mpsc::channel;
let (send, recv) = channel();

thread::spawn(move || {
    loop {
        let msg = recv.recv().unwrap();
        println!("Hello, {:?}", msg);
    }  
});

send.send("Alan").unwrap();

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