Logo

Programming-Idioms

  • Lisp
  • C++
  • PHP
  • Java
  • Python
  • JS

Idiom #25 Send a value to another thread

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

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()
#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();
}
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']);
}
https://gist.github.com/f7c174c53efaba4d8575

I tried to put in in here, but it was just too long.
import static java.lang.System.out;
import static java.lang.Thread.sleep;
class Process {
    volatile String s;
    void f() throws InterruptedException {
        Thread a = new Thread(() -> {
            try {
                sleep(1_000);
                out.println("Hello, " + s);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        a.start();
        sleep(500);
        s = "Alan";
    }
}
Process p = new Process();
p.f();

The `volatile` modifier toggles "atomic" access.

https://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html
{
  // 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
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