ArkScript
A small, lisp-inspired, functional scripting language
Future.cpp
Go to the documentation of this file.
1#include <Ark/VM/Future.hpp>
2
3#include <Ark/VM/VM.hpp>
5
6namespace Ark::internal
7{
8 UserType::ControlFuncs Future::ControlFunctions = {
9 .ostream_func = [](std::ostream& os, const UserType& user) -> std::ostream& {
10 os << "Future@" << user.data();
11 return os;
12 },
13 .deleter = [](void* data) {
14 Future* f = static_cast<Future*>(data);
15 f->deleteSelfViaVM();
16 }
17 };
18
19 // cppcheck-suppress constParameterReference
20 Future::Future(ExecutionContext* context, VM* vm, std::vector<Value>& args) :
21 m_vm(vm)
22 {
23 m_value = std::async(
24 std::launch::async,
25 [vm, context, args]() mutable {
26 const Value res = vm->resolve(context, args);
27 // We need to mark the context as free to use as soon as possible,
28 // because if we do it in `Future::resolve`, it will never be marked as free
29 // if the future is not awaited, even though it can already be reused.
30 // The value is returned as a copy by VM::resolve, and not a reference,
31 // thus it is okay to get rid of the context.
32 vm->deleteContext(context);
33 return res;
34 });
35 }
36
38 {
39 if (!m_value.valid())
40 return Nil;
41
42 m_value.wait();
43 Value res = m_value.get();
44 return res;
45 }
46
48 {
49 m_vm->deleteFuture(this);
50 }
51}
Internal object to resolve asynchronously a function call in ArkScript.
The ArkScript virtual machine.
The ArkScript virtual machine, executing ArkScript bytecode.
Definition VM.hpp:46
void deleteContext(internal::ExecutionContext *ec)
Free a given execution context.
Definition VM.cpp:396
Value resolve(internal::ExecutionContext *context, const std::vector< Value > &n)
Resolves a function call (called by plugins and builtins)
Definition VM.hpp:61
void deleteFuture(internal::Future *f)
Free a given future.
Definition VM.cpp:439
std::future< Value > m_value
The actual thread.
Definition Future.hpp:47
VM * m_vm
Non-owning pointer.
Definition Future.hpp:48
static UserType::ControlFuncs ControlFunctions
Definition Future.hpp:44
Value resolve()
Await the future, blocking the thread it is run on.
Definition Future.cpp:37
Future(ExecutionContext *context, VM *vm, std::vector< Value > &args)
Create a Future and immediately start it through std::async.
Definition Future.cpp:20
const auto Nil
ArkScript Nil value.