Name | Last modified | Size | Description | |
---|---|---|---|---|
Parent Directory | - | |||
Celix Promises are based on the OSGi Promises Specification (OSGi Compendium Release 7 Specification, Chapter 705). It follows the specification as close as possible, but some adjustments are mode for C++17.
NOTE: this implementation is still experiment and the api and behaviour will probably still change.
OSGi Compendium Release 7 Promises Specification (HTML)
OSGi Compendium Release 7 Specification (PDF)
//src/PromiseExample.cc
#include <iostream>
#include "celix/PromiseFactory.h"
static long calc_fib(long n) {
long m = 1;
long k = 0;
for (long i = 0; i <= n; ++i) {
int tmp = m + k;
m = k;
k = tmp;
}
return m;
}
celix::Promise<long> fib(celix::PromiseFactory& factory, long n) {
return factory.deferredTask<long>([n](auto deferred) {
deferred.resolve(calc_fib(n));
});
}
int main() {
celix::PromiseFactory factory{};
fib(factory, 1000000000)
.setTimeout(std::chrono::milliseconds {100})
.onSuccess([](long val) {
std::cout << "Success promise 1 : " << std::to_string(val) << std::endl;
})
.onFailure([](const std::exception& e) {
std::cerr << "Failure promise 1 : " << e.what() << std::endl;
});
fib(factory, 39)
.setTimeout(std::chrono::milliseconds{100})
.onSuccess([](long val) {
std::cout << "Success promise 2 : " << std::to_string(val) << std::endl;
})
.onFailure([](const std::exception& e) {
std::cerr << "Failure promise 2 : " << e.what() << std::endl;
});
//NOTE the program can only exit if the executor in the PromiseFactory is done executing all tasks.
}
#CMakeLists.txt
find_package(Celix REQUIRED)
add_executable(PromiseExamples src/PromiseExamples.cc)
target_link_libraries(PromiseExamples PRIVATE Celix::Promises)
Promise::setTimeout
method can be used to set a timeout on the current promise.celix::Deferred<T>::tryFail
and celix::Deferred<T>::tryResolve
can be used to resolve a promise and check if it was already resolved atomically.