Logo

Programming-Idioms

  • Go
  • 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"

#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();
}
import "fmt"
go func() {
	v := <-ch
	fmt.Printf("Hello, %v\n", v)
}()

ch <- "Alan"

The receiver goroutine blocks reading the chan string named ch.
The current goroutine sends the value to ch.
A goroutine is like a lightweight green thread.
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