This language bar is your friend. Select your favorite languages!
Select your favorite languages :
- Or search :
- Ada
- Clojure
- C++
- C#
- C#
- D
- Dart
- Elixir
- Fortran
- Go
- Haskell
- JS
- JS
- Java
- Java
- PHP
- Pascal
- Perl
- Python
- Ruby
- Rust
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.
#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();
}
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.
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.
https://gist.github.com/f7c174c53efaba4d8575
I tried to put in in here, but it was just too long.
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
https://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html
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']);
}
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.
It looks like the other implementations use queues. Due to the space limitation, I used the TIdThreadSafeStringList class from Indy for a threadsafe message queue. For standard FP code, use TThreadList with your own TObject based message.
let (send, recv) = channel();
thread::spawn(move || {
loop {
let msg = recv.recv().unwrap();
println!("Hello, {:?}", msg);
}
});
send.send("Alan").unwrap();
The message might not be printed if the main thread exits before the thread has written to stdout.