Futures and promises are constructs used in concurrent programming to handle asynchronous operations. They provide a way to retrieve values that may not be immediately available, allowing programs to continue executing while waiting for these values to be resolved.
A future represents a value that may become available at some point in the future. A promise is an object that is used to fulfill a future; once the value is available, the associated promise is completed.
Both futures and promises help manage multithreading and improve the efficiency of applications by allowing the program to proceed with other tasks while waiting for the completion of an asynchronous operation.
Here’s a simple example in PHP demonstrating the concept of futures and promises:
<?php
class Promise {
private $value;
private $resolved = false;
private $callbacks = [];
public function resolve($value) {
$this->value = $value;
$this->resolved = true;
foreach ($this->callbacks as $callback) {
$callback($value);
}
}
public function then($callback) {
if ($this->resolved) {
$callback($this->value);
} else {
$this->callbacks[] = $callback;
}
}
}
$promise = new Promise();
$promise->then(function($value) {
echo "Value: $value\n";
});
$promise->resolve("Hello, world!");
?>
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?