text
stringlengths
10
16.2k
# Chapter 4 Labeled arguments If you have a look at modules ending in Labels in the standard library, you will see that function types have annotations you did not have in the functions you defined yourself. ```ocaml # ListLabels.map;; - : f:('a -> 'b) -> 'a list -> 'b list = \<fun\> # StringLabels.sub;; - : string ->...
# Chapter 4 Labeled arguments ```ocaml # let f \~x \~y = x - y;; val f : x:int -> y:int -> int = \<fun\> # f \~y:2 \~x:3;; - : int = 1 # ListLabels.fold_left;; - : f:('acc -> 'a -> 'acc) -> init:'acc -> 'a list -> 'acc = \<fun\> # ListLabels.fold_left \[1;2;3\] \~init:0 \~f:( + );; - : int = 6 # ListLabels.fold_lef...
## 1 Optional arguments An interesting feature of labeled arguments is that they can be made optional. For optional parameters, the question mark ? replaces the tilde \~ of non-optional ones, and the label is also prefixed by ? in the function type. Default values may be given for such optional parameters. ```ocaml # l...
## 1 Optional arguments ```ocaml # test \~y:2 \~x:3 () ();; - : int \* int \* int = (3, 2, 0) # test () () \~z:1 \~y:2 \~x:3;; - : int \* int \* int = (3, 2, 1) # (test () ()) \~z:1 ;; Error: This expression has type int \* int \* int This is not a function; it cannot be applied. ``` Here (test () ()) is already (0,0...
## 2 Labels and type inference While they provide an increased comfort for writing function applications, labels and optional arguments have the pitfall that they cannot be inferred as completely as the rest of the language. You can see it in the following two examples. ```ocaml # let h' g = g \~y:2 \~x:3;; val h' : (y...
## 2 Labels and type inference We will not try here to explain in detail how type inference works. One must just understand that there is not enough information in the above program to deduce the correct type of g or bump. That is, there is no way to know whether an argument is optional or not, or which is the correct ...
## 2 Labels and type inference This transformation is coherent with the intended semantics, including side-effects. That is, if the application of optional parameters shall produce side-effects, these are delayed until the received function is really applied to an argument.
## 3 Suggestions for labeling Like for names, choosing labels for functions is not an easy task. A good labeling is one which - makes programs more readable, - is easy to remember, - when possible, allows useful partial applications. We explain here the rules we applied when labeling OCaml libraries. To speak in ...
## 3 Suggestions for labeling This principle also applies to functions of several arguments whose return type is a type variable, as long as the role of each argument is not ambiguous. Labeling such functions may lead to awkward error messages when one attempts to omit labels in an application, as we have seen with Lis...
## 3 Suggestions for labeling All these are only suggestions, but keep in mind that the choice of labels is essential for readability. Bizarre choices will make the program harder to maintain. In the ideal, the right function name with right labels should be enough to understand the function’s meaning. Since one can ge...
# OCaml - Polymorphic variants Source: https://ocaml.org/manual/5.2/polyvariant.html ☰ - [The core language](coreexamples.html) - [The module system](moduleexamples.html) - [Objects in OCaml](objectexamples.html) - [Labeled arguments](lablexamples.html) - [Polymorphic variants](polyvariant.html) - [Polymorp...
# Chapter 5 Polymorphic variants Variants as presented in section ‍[1.4](coreexamples.html#s%3Atut-recvariants) are a powerful tool to build data structures and algorithms. However they sometimes lack flexibility when used in modular programming. This is due to the fact that every constructor is assigned to a unique ty...
## 1 Basic use In programs, polymorphic variants work like usual ones. You just have to prefix their names with a backquote character \`. ```ocaml # \[\`On; \`Off\];; - : \[\> \`Off \| \`On \] list = \[\`On; \`Off\] # \`Number 1;; - : \[\> \`Number of int \] = \`Number 1 # let f = function \`On -> 1 \| \`Off -> 0 \| ...
## 1 Basic use ```ocaml # type 'a vlist = \[\`Nil \| \`Cons of 'a \* 'a vlist\];; type 'a vlist = \[ \`Cons of 'a \* 'a vlist \| \`Nil \] # let rec map f : 'a vlist -> 'b vlist = function \| \`Nil -> \`Nil \| \`Cons(a, l) -> \`Cons(f a, map f l) ;; val map : ('a -> 'b) -> 'a vlist -> 'b vlist = \<fun\> ```
## 2 Advanced use Type-checking polymorphic variants is a subtle thing, and some expressions may result in more complex type information. ```ocaml # let f = function \`A -> \`C \| \`B -> \`D \| x -> x;; val f : (\[\> \`A \| \`B \| \`C \| \`D \] as 'a) -> 'a = \<fun\> # f \`E;; - : \[\> \`A \| \`B \| \`C \| \`D \| \`E ...
## 2 Advanced use Even if a value has a fixed variant type, one can still give it a larger type through coercions. Coercions are normally written with both the source type and the destination type, but in simple cases the source type may be omitted. ```ocaml # type 'a wlist = \[\`Nil \| \`Cons of 'a \* 'a wlist \| \`Sn...
## 2 Advanced use ```ocaml # let num x = \`Num x let eval1 eval (\`Num x) = x let rec eval x = eval1 eval x ;; val num : 'a -> \[\> \`Num of 'a \] = \<fun\> val eval1 : 'a -> \[\< \`Num of 'b \] -> 'b = \<fun\> val eval : \[\< \`Num of 'a \] -> 'a = \<fun\> # let plus x y = \`Plus(x,y) let eval2 eval = function \| \`P...
## 3 Weaknesses of polymorphic variants After seeing the power of polymorphic variants, one may wonder why they were added to core language variants, rather than replacing them. The answer is twofold. The first aspect is that while being pretty efficient, the lack of static type information allows for less optimization...
## 3 Weaknesses of polymorphic variants You can avoid such risks by annotating the definition itself. ```ocaml # let f : abc -> string = function \| \`As -> "A" \| #abc -> "other" ;; Error: This pattern matches values of type \[? \`As \] but a pattern was expected which matches values of type abc The second variant typ...
# OCaml - Polymorphism and its limitations Source: https://ocaml.org/manual/5.2/polymorphism.html ☰ - [The core language](coreexamples.html) - [The module system](moduleexamples.html) - [Objects in OCaml](objectexamples.html) - [Labeled arguments](lablexamples.html) - [Polymorphic variants](polyvariant.html) ...
# Chapter 6 Polymorphism and its limitations This chapter covers more advanced questions related to the limitations of polymorphic functions and types. There are some situations in OCaml where the type inferred by the type checker may be less generic than expected. Such non-genericity can stem either from interactions ...
## 1 Weak polymorphism and mutation
### 1.1 Weakly polymorphic types Maybe the most frequent examples of non-genericity derive from the interactions between polymorphic types and mutation. A simple example appears when typing the following expression ```ocaml # let store = ref None ;; val store : '\_weak1 option ref = {contents = None} ``` Since the type...
### 1.1 Weakly polymorphic types ```ocaml # let swap store x = match !store with \| None -> store := Some x; x \| Some y -> store := Some x; y;; val swap : 'a option ref -> 'a -> 'a = \<fun\> ``` We can apply this function to our store ```ocaml # let one = swap store 1 let one_again = swap store 2 let two = swap store ...
### 1.1 Weakly polymorphic types Moreover, weak types cannot appear in the signature of toplevel modules: types must be known at compilation time. Otherwise, different compilation units could replace the weak type with different and incompatible types. For this reason, compiling the following small piece of code le...
### 1.2 The value restriction Identifying the exact context in which polymorphic types should be replaced by weak types in a modular way is a difficult question. Indeed the type system must handle the possibility that functions may hide persistent mutable states. For instance, the following function uses an internal re...
### 1.2 The value restriction Quite often, this happens when defining functions using higher order functions. To avoid this problem, a solution is to add an explicit argument to the function: ```ocaml # let id_again = fun x -> (fun x -> x) (fun x -> x) x;; val id_again : 'a -> 'a = \<fun\> ``` With this argument, id_ag...
### 1.3 The relaxed value restriction There is another partial solution to the problem of unnecessary weak types, which is implemented directly within the type checker. Briefly, it is possible to prove that weak types that only appear as type parameters in covariant positions –also called positive positions– can be saf...
### 1.4 Variance and value restriction Variance describes how type constructors behave with respect to subtyping. Consider for instance a pair of type x and xy with x a subtype of xy, denoted x :> xy: ```ocaml # type x = \[ \`X \];; type x = \[ \`X \] # type xy = \[ \`X \| \`Y \];; type xy = \[ \`X \| \`Y \] ``` As x ...
### 1.4 Variance and value restriction In this case, we have x :> xy implies xy proc :> x proc. Notice that the second subtyping relation reverse the order of x and xy: the type constructor 'a proc is contravariant in its parameter 'a. More generally, the function type constructor 'a -> 'b is covariant in its return ty...
### 1.5 Abstract data types Moreover, when the type definitions are exposed, the type checker is able to infer variance information on its own and one can benefit from the relaxed value restriction even unknowingly. However, this is not the case anymore when defining new abstract types. As an illustration, we can defin...
## 2 Polymorphic recursion The second major class of non-genericity is directly related to the problem of type inference for polymorphic functions. In some circumstances, the type inferred by OCaml might be not general enough to allow the definition of some recursive functions, in particular for recursive functions act...
## 2 Polymorphic recursion Non-regular recursive algebraic data types correspond to polymorphic algebraic data types whose parameter types vary between the left and right side of the type definition. For instance, it might be interesting to define a datatype that ensures that all lists are nested at the same depth: ```...
## 2 Polymorphic recursion The type error here comes from the fact that during the definition of depth, the type checker first assigns to depth the type 'a -> 'b . When typing the pattern matching, 'a -> 'b becomes 'a nested -> 'b, then 'a nested -> int once the List branch is typed. However, when typing the applicatio...
### 2.1 Explicitly polymorphic annotations The solution of this conundrum is to use an explicitly polymorphic type annotation for the type 'a: ```ocaml # let rec depth: 'a. 'a nested -> int = function \| List \_ -> 1 \| Nested n -> 1 + depth n;; val depth : 'a nested -> int = \<fun\> # depth ( Nested(List \[ \[7\]; \[...
### 2.1 Explicitly polymorphic annotations ```ocaml # let sum: 'a 'b 'c. 'a -> 'b -> 'c = fun x y -> x + y;; Error: This definition has type int -> int -> int which is less general than 'a 'b 'c. 'a -> 'b -> 'c ``` An important remark here is that it is not needed to explicit fully the type of depth: it is sufficient t...
### 2.2 More examples With explicit polymorphic annotations, it becomes possible to implement any recursive function that depends only on the structure of the nested lists and not on the type of the elements. For instance, a more complex example would be to compute the total number of elements of the nested lists: ```o...
### 2.2 More examples ```ocaml # let shape n = let rec shape: 'a 'b. ('a nested -> int nested) -> ('b list list -> 'a list) -> 'b nested -> int nested = fun nest nested_shape -> function \| List l -> raise (Invalid_argument "shape requires nested_list of depth greater than 1") \| Nested (List l) -> nest @@ List (nested...
## 3 Higher-rank polymorphic functions Explicit polymorphic annotations are however not sufficient to cover all the cases where the inferred type of a function is less general than expected. A similar problem arises when using polymorphic functions as arguments of higher-order functions. For instance, we may want to co...
## 3 Higher-rank polymorphic functions val average: ('a. 'a nested -> int) -> 'a nested -> 'b nested -> int Note that this syntax is not valid within OCaml: average has an universally quantified type 'a inside the type of one of its argument whereas for polymorphic recursion the universally quantified type was intr...
## 3 Higher-rank polymorphic functions ```ocaml # let average (obj:\<f:'a. 'a nested -> \_ \> ) x y = (obj#f x + obj#f y) / 2 ;; val average : \< f : 'a. 'a nested -> int \> -> 'b nested -> 'c nested -> int = \<fun\> ``` ------------------------------------------------------------------------ [« Polymorphic variants](p...
# OCaml - Generalized algebraic datatypes Source: https://ocaml.org/manual/5.2/gadts-tutorial.html ☰ - [The core language](coreexamples.html) - [The module system](moduleexamples.html) - [Objects in OCaml](objectexamples.html) - [Labeled arguments](lablexamples.html) - [Polymorphic variants](polyvariant.html)...
# Chapter 7 Generalized algebraic datatypes Generalized algebraic datatypes, or GADTs, extend usual sum types in two ways: constraints on type parameters may change depending on the value constructor, and some type variables may be existentially quantified. Adding constraints is done by giving an explicit return type, ...
## 1 Recursive functions We write an eval function: let rec eval : type a. a term -> a = function \| Int n -> n (\* a = int \*) \| Add -> (fun x y -> x+y) (\* a = int -> int -> int \*) \| App(f,x) -> (eval f) (eval x) (\* eval called at types (b->a) and b for fresh b \*) And use it: let two = eval (App (App (Add, Int 1...
## 1 Recursive functions In absence of an explicit polymorphic annotation, a monomorphic type is inferred for the recursive function. If a recursive call occurs inside the function definition at a type that involves an existential GADT type variable, this variable flows to the type of the recursive function, and thus e...
## 2 Type inference Type inference for GADTs is notoriously hard. This is due to the fact some types may become ambiguous when escaping from a branch. For instance, in the Int case above, n could have either type int or a, and they are not equivalent outside of that branch. As a first approximation, type inference will...
## 2 Type inference Here the return type int is never mixed with a, so it is seen as non-ambiguous, and can be inferred. When using such partial type annotations we strongly suggest specifying the -principal mode, to check that inference is principal. The exhaustiveness check is aware of GADT constraints, and can autom...
## 3 Refutation cases Usually, the exhaustiveness check only tries to check whether the cases omitted from the pattern matching are typable or not. However, you can force it to try harder by adding *refutation cases*, written as a full stop. In the presence of a refutation case, the exhaustiveness check will first comp...
## 3 Refutation cases Another addition is that the redundancy check is now aware of GADTs: a case will be detected as redundant if it could be replaced by a refutation case using the same pattern.
## 4 Advanced examples The term type we have defined above is an *indexed* type, where a type parameter reflects a property of the value contents. Another use of GADTs is *singleton* types, where a GADT value represents exactly one type. This value can be used as runtime representation for this type, and a function rec...
## 4 Advanced examples let rec eq_type : type a b. a typ -> b typ -> (a,b) eq option = fun a b -> match a, b with \| Int, Int -> Some Eq \| String, String -> Some Eq \| Pair(a1,a2), Pair(b1,b2) -> begin match eq_type a1 b1, eq_type a2 b2 with \| Some Eq, Some Eq -> Some Eq \| \_ -> None end \| \_ -> None type dyn = Dyn...
## 5 Existential type names in error messages The typing of pattern matching in the presence of GADTs can generate many existential types. When necessary, error messages refer to these existential types using compiler-generated names. Currently, the compiler generates these names according to the following nomenclature...
## 6 Explicit naming of existentials As explained above, pattern-matching on a GADT constructor may introduce existential types. Syntax has been introduced which allows them to be named explicitly. For instance, the following code names the type of the argument of f and uses this name. type \_ closure = Closure : ('a -...
## 7 Equations on non-local abstract types GADT pattern-matching may also add type equations to non-local abstract types. The behaviour is the same as with local abstract types. Reusing the above eq type, one can write: module M : sig type t val x : t val e : (t,int) eq end = struct type t = int let x = 33 let e = Eq e...
# OCaml - Advanced examples with classes and modules Source: https://ocaml.org/manual/5.2/advexamples.html ☰ - [The core language](coreexamples.html) - [The module system](moduleexamples.html) - [Objects in OCaml](objectexamples.html) - [Labeled arguments](lablexamples.html) - [Polymorphic variants](polyvaria...
# Chapter 8 Advanced examples with classes and modules In this chapter, we show some larger examples using objects, classes and modules. We review many of the object features simultaneously on the example of a bank account. We show how modules taken from the standard library can be expressed as classes. Lastly, we desc...
## 1 Extended example: bank accounts In this section, we illustrate most aspects of Object and inheritance by refining, debugging, and specializing the following initial naive definition of a simple bank account. (We reuse the module Euro defined at the end of chapter ‍[3](objectexamples.html#c%3Aobjectexamples).) ```o...
## 1 Extended example: bank accounts We make the method interest private, since clearly it should not be called freely from the outside. Here, it is only made accessible to subclasses that will manage monthly or yearly updates of the account. We should soon fix a bug in the current definition: the deposit method can be...
## 1 Extended example: bank accounts ```ocaml # type 'a operation = Deposit of 'a \| Retrieval of 'a;; type 'a operation = Deposit of 'a \| Retrieval of 'a # class account_with_history = object (self) inherit safe_account as super val mutable history = \[\] method private trace x = history \<- x :: history method depo...
## 1 Extended example: bank accounts class account_with_deposit : Euro.c -> object val mutable balance : Euro.c val mutable history : Euro.c operation list method balance : Euro.c method deposit : Euro.c -> unit method history : Euro.c operation list method private trace : Euro.c operation -> unit method withdraw : Eur...
## 1 Extended example: bank accounts ```ocaml # let today () = (01,01,2000) (\* an approximation \*) module Account (M:MONEY) = struct type m = M.c let m = new M.c let zero = m 0. class bank = object (self) val mutable balance = zero method balance = balance val mutable history = \[\] method private trace x = history \...
## 1 Extended example: bank accounts The class bank is the *real* implementation of the bank account (it could have been inlined). This is the one that will be used for further extensions, refinements, etc. Conversely, the client will only be given the client view. ```ocaml # module Euro_account = Account(Euro);; # mod...
## 1 Extended example: bank accounts The functor Client may also be redefined when some new features of the account can be given to the client. ```ocaml # module Internet_account (M : MONEY) = struct type m = M.c module A = Account(M) class bank = object inherit A.bank method mail s = print_string s end class type clie...
## 2 Simple modules as classes One may wonder whether it is possible to treat primitive types such as integers and strings as objects. Although this is usually uninteresting for integers or strings, there may be some situations where this is desirable. The class money above is such an example. We show here how to do it...
### 2.1 Strings A naive definition of strings as objects could be: ```ocaml # class ostring s = object method get n = String.get s n method print = print_string s method escaped = new ostring (String.escaped s) end;; ``` class ostring : string -> object method escaped : ostring method get : int -> char method print : u...
### 2.1 Strings Another difficulty is the implementation of the method concat. In order to concatenate a string with another string of the same class, one must be able to access the instance variable externally. Thus, a method repr returning s must be defined. Here is the correct definition of strings: ```ocaml # class...
#### Stacks There is sometimes an alternative between using modules or classes for parametric data types. Indeed, there are situations when the two approaches are quite similar. For instance, a stack can be straightforwardly implemented as a class: ```ocaml # exception Empty;; ``` exception Empty ```ocaml # class \['a\...
### 2.1 Strings A better solution is to use polymorphic methods, which were introduced in OCaml version 3.05. Polymorphic methods makes it possible to treat the type variable 'b in the type of fold as universally quantified, giving fold the polymorphic type Forall 'b. ('b -> 'a -> 'b) -> 'b -> 'b. An explicit type decl...
### 2.2 Hashtbl A simplified version of object-oriented hash tables should have the following class type. ```ocaml # class type \['a, 'b\] hash_table = object method find : 'a -> 'b method add : 'a -> 'b -> unit end;; ``` class type \['a, 'b\] hash_table = object method add : 'a -> 'b -> unit method find : 'a -> 'b end...
### 2.3 Sets Implementing sets leads to another difficulty. Indeed, the method union needs to be able to access the internal representation of another object of the same class. This is another instance of friend functions as seen in section ‍[3.17](objectexamples.html#s%3Afriends). Indeed, this is the same mechanism us...
## 3 The subject/observer pattern The following example, known as the subject/observer pattern, is often presented in the literature as a difficult inheritance problem with inter-connected classes. The general pattern amounts to the definition a pair of two classes that recursively interact with one another. The class ...
## 3 The subject/observer pattern ```ocaml # type event = Raise \| Resize \| Move;; type event = Raise \| Resize \| Move # let string_of_event = function Raise -> "Raise" \| Resize -> "Resize" \| Move -> "Move";; val string_of_event : event -> string = \<fun\> # let count = ref 0;; val count : int ref = {contents = 0...
## 3 The subject/observer pattern ```ocaml # let window_observer = new window_observer;; val window_observer : (\< draw : unit; .. \> as '\_weak4) window_observer = \<obj> # window#add_observer window_observer;; - : unit = () # window#move 1;; ``` {Position = 1} - : unit = () Classes window_observer and window_subjec...
## 3 The subject/observer pattern ```ocaml # class \['subject\] trace_observer = object inherit \['subject, event\] observer method notify s e = Printf.printf "\<Window %d \<== %s>\\n" s#identity (string_of_event e) end;; ``` class \['a\] trace_observer : object constraint 'a = \< identity : int; .. \> method notify : ...
# OCaml - Parallel programming Source: https://ocaml.org/manual/5.2/parallelism.html ☰ - [The core language](coreexamples.html) - [The module system](moduleexamples.html) - [Objects in OCaml](objectexamples.html) - [Labeled arguments](lablexamples.html) - [Polymorphic variants](polyvariant.html) - [Polymorp...
# Chapter 9 Parallel programming In this chapter, we shall look at the parallel programming facilities in OCaml. The OCaml standard library exposes low-level primitives for parallel programming. We recommend the users to utilise higher-level parallel programming libraries such as [domainslib](https://github.com/ocaml-m...
## 1 Domains Domains are the units of parallelism in OCaml. The module [Domain](../5.2/api/Domain.html) provides the primitives to create and manage domains. New domains can be spawned using the spawn function. Domain.spawn (fun \_ -> print_endline "I ran in parallel") I ran in parallel - : unit Domain.t = \<abstr> The...
### 1.1 Joining domains We shall use the program to compute the nth Fibonacci number using recursion as a running example. The sequential program for computing the nth Fibonacci number is given below. (\* fib.ml \*) let n = try int_of_string Sys.argv.(1) with \_ -> 1 let rec fib n = if n \< 2 then 1 else fib (n - 1) + ...
### 1.1 Joining domains The program spawns two domains which compute the nth Fibonacci number. The spawn function returns a Domain.t value which can be joined to get the result of the parallel computation. The join function blocks until the computation runs to completion. $ ocamlopt -o fib_twice.exe fib_twice.ml ...
## 2 Domainslib: A library for nested-parallel programming Let us attempt to parallelise the Fibonacci function. The two recursive calls may be executed in parallel. However, naively parallelising the recursive calls by spawning domains for each one will not work as it spawns too many domains. (\* fib_par1.ml \*) let n...
### 2.1 Parallelising Fibonacci using domainslib The OCaml standard library provides only low-level primitives for concurrent and parallel programming, leaving high-level programming libraries to be developed and distributed outside the core compiler distribution. [Domainslib](https://github.com/ocaml-multicore/domains...
### 2.1 Parallelising Fibonacci using domainslib let main () = let pool = T.setup_pool ~num_domains:(num_domains - 1) () in let res = T.run pool (fun _ -> fib_par pool n) in T.teardown_pool pool; Printf.printf "fib(%d) = %d\n" n res let _ = main () The program takes the number of domains...
### 2.1 Parallelising Fibonacci using domainslib For simplicity, we use ocamlfind to compile this program. It is recommended that the users use [dune](https://github.com/ocaml/dune) to build their programs that utilise libraries installed through [opam](https://opam.ocaml.org/). $ ocamlfind ocamlopt -package domain...
### 2.2 Parallel iteration constructs Many numerical algorithms use for-loops. The parallel-for primitive provides a straight-forward way to parallelise such code. Let us take the [spectral-norm](https://benchmarksgame-team.pages.debian.net/benchmarksgame/description/spectralnorm.html#spectralnorm) benchmark from the c...
### 2.2 Parallel iteration constructs The parallel version of spectral norm is shown below. (* spectralnorm_par.ml *) let num_domains = try int_of_string Sys.argv.(1) with _ -> 1 let n = try int_of_string Sys.argv.(2) with _ -> 32 let eval_A i j = 1. /. float((i+j)*(i+j+1)/2+i+1) module T = Domainsl...
### 2.2 Parallel iteration constructs Observe that the parallel_for function is isomorphic to the for-loop in the sequential version. No other change is required except for the boiler plate code to set up and tear down the pools. $ ocamlopt -o spectralnorm.exe spectralnorm.ml $ ocamlfind ocamlopt -package domai...
### 2.2 Parallel iteration constructs On the author’s machine, the program scales reasonably well up to 4 domains but performs worse with 8 domains. Recall that the machine only has 4 physical cores. Debugging and fixing this performance issue is beyond the scope of this tutorial.
## 3 Parallel garbage collection An important aspect of the scalability of parallel OCaml programs is the scalability of the garbage collector (GC). The OCaml GC is designed to have both low latency and good parallel scalability. OCaml has a generational garbage collector with a small minor heap and a large major heap....
## 4 Memory model: The easy bits Modern processors and compilers aggressively optimise programs. These optimisations accelerate without otherwise affecting sequential programs, but cause surprising behaviours to be visible in parallel programs. To benefit from these optimisations, OCaml adopts a relaxed memory model th...
## 4 Memory model: The easy bits Importantly, for data race free (DRF) programs, OCaml provides sequentially consistent (SC) semantics – the observed behaviour of such programs can be explained by the interleaving of operations from different domains. This property is known as DRF-SC guarantee. Moreover, in OCaml, DRF-...
## 5 Blocking synchronisation Domains may perform blocking synchronisation with the help of [Mutex](../5.2/api/Mutex.html), [Condition](../5.2/api/Condition.html) and [Semaphore](../5.2/api/Semaphore.html) modules. These modules are the same as those used to synchronise threads created by the threads library (chapter [...
## 5 Blocking synchronisation The push operation locks the mutex, updates the contents field with a new list whose head is the element being pushed and the tail is the old list. The condition variable nonempty is signalled while the lock is held in order to wake up any domains waiting on this condition. If there are wa...
### 5.1 Interaction with systhreads How do systhreads interact with domains? The systhreads created on a particular domain remain pinned to that domain. Only one systhread at a time is allowed to run OCaml code on a particular domain. However, systhreads belonging to a particular domain may run C library or system code...
### 5.1 Interaction with systhreads $ ocamlopt -I +threads unix.cmxa threads.cmxa -o dom_thr.exe dom_thr.ml $ ./dom_thr.exe Thread 1 running on domain 1 saw initial write Thread 0 running on domain 0 saw the write by thread 1 Thread 2 running on domain 1 saw the write by thread 0 Thread 3 runnin...
## 6 Interaction with C bindings During parallel execution with multiple domains, C code running on a domain may run in parallel with any C code running in other domains even if neither of them has released the “domain lock”. Prior to OCaml 5.0, C bindings may have assumed that if the OCaml runtime lock is not released...
## 7 Atomics Mutex, condition variables and semaphores are used to implement blocking synchronisation between domains. For non-blocking synchronisation, OCaml provides [Atomic](../5.2/api/Atomic.html) variables. As the name suggests, non-blocking synchronisation does not provide mechanisms for suspending and waking up ...
## 7 Atomics Observe that the load and the store are two separate operations, and the increment operation as a whole is not performed atomically. When two domains execute this code in parallel, both of them may read the same value of the counter curr and update it to curr + 1. Hence, instead of two increments, the effe...
### 7.1 Lock-free stack The Atomic module is used to implement non-blocking, lock-free data structures. The following program implements a lock-free stack. module Lockfree_stack : sig type 'a t val make : unit -> 'a t val push : 'a t -> 'a -> unit val pop : 'a t -> 'a option end = struct type 'a t = 'a list Atomic.t le...
### 7.1 Lock-free stack [« Advanced examples with classes and modules](advexamples.html)[Memory model: The hard bits »](memorymodel.html) Copyright © 2024 Institut National de Recherche en Informatique et en Automatique ------------------------------------------------------------------------
# OCaml - Memory model: The hard bits Source: https://ocaml.org/manual/5.2/memorymodel.html ☰ - [The core language](coreexamples.html) - [The module system](moduleexamples.html) - [Objects in OCaml](objectexamples.html) - [Labeled arguments](lablexamples.html) - [Polymorphic variants](polyvariant.html) - [P...