Skip to content
Fetching contributors…
Cannot retrieve contributors at this time
360 lines (275 sloc) 12.6 KB
Copyright © 2011 MLstate
This file is part of OPA.
OPA is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License, version 3, as published by
the Free Software Foundation.
OPA is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
more details.
You should have received a copy of the GNU Affero General Public License
along with OPA. If not, see <>.
Runtime library for continuations and concurrency.
The role of this library is to provide the necessary primitives introduced by the Cps transformation,
to be used at runtime.
This library is meant to be used
- directly by low-level libraries (appserver, db3)
- transparently by the QML CPS-based compiler
Beware, by hacking this lib, you should update QmlCpsRewriter consistently
@author David Rajchenbach-Teller
@author Mathieu Barbin
{6 Continuations}
type continuation_options =
movable : bool;
(**[true] if the continuation may be stolen by another server,
[false] otherwise*)
atomic : bool;
(**[true] if the continuation should not be scheduled.
This can cause runtime errors if the continuation contains [wait].*)
_lazy : bool;
(**[true] if the continuation should be evaluated rather than scheduled.*)
(**A mechanism for returning values of type ['a].
Optimized implementations should make this a [goto].*)
type 'a continuation
type 'a func0 = 'a continuation -> unit
(**The implementation of a function with type ['a -> 'b], after cps-transfo*)
type ('a, 'b) func = 'a -> 'b func0
(**The default options for continuations: movable.*)
val default_options : continuation_options
(** create a cont from its fields : not used currently by the generated code *)
val make_cont: continuation_options -> QmlClosureRuntime.t -> 'a continuation
val make_cont_ml: continuation_options -> ('a -> unit) -> 'a continuation
(** a short name because of the number of occurrences in the generated code *)
val cont: QmlClosureRuntime.t -> 'a continuation
val cont_ml: ('a -> unit) -> 'a continuation
(** creating a cont from an other cont, changing nothing but the payload
this function is used in the generated code to be able to pass the thread context *)
val ccont : 'b continuation -> QmlClosureRuntime.t -> 'a continuation
val ccont_ml : 'b continuation -> ('a -> unit) -> 'a continuation
(**Return a value using a continuation : apply the continuation to the value *)
val return : 'a continuation -> 'a -> unit
(** Like [return] but can't be schedule before return value to
continuation. *)
val execute : 'a continuation -> 'a -> unit
val update_cont : 'a continuation -> _ continuation option -> string -> string -> _ -> 'a continuation
val print_trace : 'a continuation -> unit
(** [push_cont k x] Like return but asynchronous. Create a task that
apply the continuation to the value, and push it to the cps
scheduler. *)
val push_cont : 'a continuation -> 'a -> unit
(** {6 thread context} *)
Setting and accessing the \@thread_context from a continuation. If the thread_context has not been set with
[with_thread_context], the returned value is [None]. Otherwise, [thread_context] returns the
last context set by [with_thread_context].
Implementation uses type [Obj.t], which means that you should carrefully use the pair [thread_context/with_thread_context].
In practice, these two functions are not used directly, but are exported in the bsl with the tag [restricted:cps],
which means that they can be used only be code generated by [QmlCpsRewriter], from the 2 following directives (available
in opa and qml) :
+ \@thread_context
+ \@with_thread_context
@see "thread_context.opa" from the stdlib of opa to see how the final user can use this feature.
(** *)
val thread_context : 'a continuation -> 'thread_context option
val with_thread_context : 'thread_context -> 'a continuation -> 'a continuation
(** Similar to thread_context, but for a specific purpose *)
val transaction_context : 'a continuation -> 'transaction_context option
val with_transaction_context : 'transaction_context -> 'a continuation -> 'a continuation
(** {6 exceptions} *)
(** Used to get the exception-handling continuation *)
val handler_cont: 'a continuation -> 'exc continuation
(** Catches exceptions thrown within the continuation *)
val catch : QmlClosureRuntime.t -> 'a continuation -> 'a continuation
val catch_ml : ('exc -> 'a continuation -> unit) -> 'a continuation -> 'a continuation
(** Stores and retrieves backtrace data on a cyclic queue. *)
val bt_add : string -> unit
val bt_take : unit -> string
(** Prints a function name and value of its arguments (treated by obj.magic) *)
(* TODO: due to limitation of libbsl, it's only the first argument for now *)
val fun_args2string : string -> 'a -> string
(* The argument is the first world displayed, e.g. "Raised" or "Interrupted" *)
val display_backtrace : string -> unit
(** {6 Call-cc : uncps} *)
val uncps : string -> 'a continuation -> QmlClosureRuntime.t -> 'b
val uncps_ml:
string ->
'a continuation ->
('b continuation -> unit) -> 'b
(**callcc_directive : the real version of call-cc (used in resolution of directive \@callcc) *)
val callcc_directive : (* (('a continuation, unit) func, 'a) func *)
(* f : *) ( 'a continuation -> 'unit continuation -> unit ) ->
'a continuation ->
(** Apply a function to an argument.
In concurrent implementations, this application can also
have an effect on scheduling and/or garbage-collection.
@TODO When a prototype is complete, add hand-optimized
[apply2], [apply3]...*)
val apply: ('a, 'b) func -> 'a -> 'b continuation -> unit
(*val apply: ('a, 'b) func -> 'b continuation -> 'a -> unit*)
Instead of apply2, apply3, we use apply0 :
apply3 f x y z k ==> apply0 (fun () -> f x y z k) k
The ml closure is created anyway inside apply-n.
K is repassed because we need some other infos from it.
val apply0: QmlClosureRuntime.t -> 'b continuation -> unit
val apply0_ml : (unit -> unit) -> 'b continuation -> unit
{6 Futures}
Future are used for evaluation in pseudo-concurrency.
(**A value of type ['a], which may already have been computed
or may be computed as a background task.*)
type 'a future
val spawn: (unit -> 'a continuation -> unit) -> 'a future
val wait: 'a future -> 'a continuation -> unit
(** exported low-level barrier management for top level value *)
Creating a new barrier.
ignored argument : because QmlServerLib.empty is not unit.
For optimization purpose, we does not want to project this bypass *)
val make_barrier : string -> 'a future
(** Print a barrier *)
val print_barrier : Format.formatter -> 'a future -> unit
Releasing a barrier means provide its terminaison value.
+ <!> Barrier should be released only once, or it would cause
an internal error.
+ <!> Releasing a barrier leads to compute all pending continuation
related to this barrier. The function returns only when all pending
continuation have been computed. In practice, a pending continuation
of a barrier is a continuation which only {e push} a task using the
release value in the main queue, but does not do real computation.
val release_barrier : 'a future -> 'a -> unit
Check if a barrier has been released.
Used for rewritting the top-level.
The function returns [true] if the barrier is computed,
or if an exception occurred during the computation of the barrier.
val is_released : _ future -> bool
(** Initialize some structure for a future use of [toplevel_wait]. *)
val before_wait : 'projection_friendly -> unit
Check if the barrier was realeased and returns the computed value
else raise a [Failure].
This function is specially used only for toplevel rewritting.
val toplevel_wait : 'a future -> 'a
(** {6 Magic} *)
Because of ocaml generalization error on value restriction, we need to
deal with black_barrier to evoid the apparition of Obj.magic everywhere
using these [black_*] function is the default behavior of back-ends,
using MLSTATE_QMLC_NO_MAGIC (debug env toggle) will make the back-ends
not use them.
Essentially, these function are implemented with Obj.magic,
but the type transformation is more specific, to loose less type informations,
and potentially catch more errors.
(** *)
val magic_cont : 'a continuation -> 'b continuation
val magic_func : ('a, 'b) func -> ('c, 'd) func
val magic_func0 : (_ func0) -> _ func0
val magic_func1 : (_ -> _ func0) -> (_ -> _ func0)
val magic_func2 : (_ -> _ -> _ func0) -> (_ -> _ -> _ func0)
val magic_func3 : (_ -> _ -> _ -> _ func0) -> (_ -> _ -> _ -> _ func0)
val magic_func4 : (_ -> _ -> _ -> _ -> _ func0) -> (_ -> _ -> _ -> _ -> _ func0)
val magic_func5 : (_ -> _ -> _ -> _ -> _ -> _ func0) -> (_ -> _ -> _ -> _ -> _ -> _ func0)
val magic_func_more : _ -> _
type black_future
val black_make_barrier : string -> black_future
val black_release_barrier : black_future -> 'a -> unit
val black_toplevel_wait : black_future -> 'a
(** {6 A few useful functions} *)
(** Open this module for duck-style cps-programming©. This is a variant from
libbase/Cps that assumes your continuations are QmlCps-continuations, not
See guidelines in libbase/Cps; as an exception, when we need conversion
between functions and continuations, we write: {[
f @> ccont_ml k
@> fun x -> x+1 |> k
While this forces us to relax the type of [@>], it keeps the readability
and avoids added parentheses.
module Ops : sig
(** Duck operator: apply a cps-function to a continuation (['a] should normally
be a continuation and ['b] unit, but keeping it polymorph is easier when
dealing with continuations-as-functions *)
val (@>) : ('a -> 'b) -> 'a -> 'b
(** The pipe operator: pass a computed value to your continuation *)
val (|>) : 'a -> 'a continuation -> unit
(** Just like List.fold_left, but in Cps. While coding a cps-fold based on
List.fold is a fun exercise, it's less efficient. *)
val fold_list : ('acc -> 'a -> 'acc continuation -> unit) -> 'acc -> 'a list -> 'acc continuation -> unit
(** Maps the given cps function on the elements of the list, in parallel *)
val map_list : ('a -> 'b continuation -> unit) -> 'a list -> 'b list continuation -> unit
(** Iters the given cps function on the elements of the list, in parallel *)
val iter_list : ('a -> unit continuation -> unit) -> 'a list -> unit continuation -> unit
val fold_array : ('acc -> 'a -> 'acc continuation -> unit) -> 'acc -> 'a array -> 'acc continuation -> unit
{6 Tasks}
type task (*A very lightweight thread.*)
val task_of_fun: unit continuation -> task (*Create a new task.*)
val push: task -> unit (*Schedule a task for execution.*)
(*If a task is waiting to be executed, remove it from the queue
and return it.*)
val steal: unit -> task option
{6 Interaction with asynchronous I/O}
These functions provide support for interacting
with the asynchronous IO features provided
by most operating systems.
Prepare a callback for a function which may be called non-deterministically.
Use [callback_of_fun] whenever you intend to invoke
an asynchronous function that will only
inform the system of its termination by calling a callback.
For instance, assume the existence of a function
[async_read_contents: file -> (string -> unit)].
This function, provided by the Operating System,
opens a file for reading, reads in the background
and eventually sends the result of reading to some callback.
In order to ensure nice cooperation
with the scheduler, we wish this function
to be seen as [read_contents: file -> string future].
Calling [callback_of_fun f] produces a pair [(cb, future)],
where [cb] does the same computation
as [f] but the result may be consulted from [future].
To adapt [async_read_contents], we may just define [read_contents] as
let read_contents file =
let (cb, future) = callback_of_fun (fun x -> x) in
callback_of_fun file cb;
type ('a, 'b) pair = {f_0: 'a; f_1: 'b}(*TODO: Get rid of this?*)
val callback_of_fun: ('a -> 'b) -> (('a -> unit), 'b future) pair
Simplified version of [callback_of_fun] for most common cases.
This is equivalent to [callback_of_fun (fun x -> x)], just slightly faster.
val callback_post: unit -> (('a -> unit), 'a future) pair
Something went wrong with that request. Please try again.