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
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.
#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();
}