Mantis Bug Tracker

View Issue Details Jump to Notes ] Issue History ] Print ]
IDProjectCategoryView StatusDate SubmittedLast Update
0007043OCamlstandard librarypublic2015-11-15 20:542017-04-13 13:07
Reportergerd 
Assigned To 
PrioritynormalSeverityfeatureReproducibilityhave not tried
StatusacknowledgedResolutionopen 
PlatformOSOS Version
Product Version4.02.3 
Target VersionFixed in Version 
Summary0007043: atomic_init, compare_and_swap, atomic_add
DescriptionWhen developing a library, there are sometimes situations where you don't know whether it is used in a multi-threaded program or not. It would be nice to have some very basic primitives that work under these circumstances, in particular a version of compare_and_swap:

val atomic_init : 'a option ref -> 'a -> 'a

with the meaning: if the variable is None, it is atomically set to the new value and the value is returned. If the variable is Some x, the value x is returned.

A possible implementation with the current runtime is:

let atomic_init var new_val =
  let new_val_opt = Some new_val in
  match !var with
    | None -> var := new_val_opt; new_val
    | Some x -> x

Looks trivial, but it is not. It is exploiting that the code after "match" cannot be interrupted. If you e.g. move the new_val_opt allocation inside "match" the function would not be working anymore.

Because it is exploiting implementation details of the current runtime, it should be part of the standard library (Pervasives, not Thread, so you always have it).

atomic_init is useful for initializing variables only once. A generalization would be:

val compare_and_swap : 'a ref -> 'a -> 'a -> bool

with the meaning: if the variable has the old value it changed to the new value, and it is returned whether the update occurred:

let compare_and_swap var old_val new_val =
  !var == old_val
   && ( var := new_val; true )

On the wish list is also atomic arithmetic, like

val atomic_add : int ref -> int -> int

which adds the number to the variable and returns the new value. (But this is not as important.)

These primitives seem to be safe to support even for alternate runtimes that permit more parallelization, because there is support for these operations in all modern CPUs.
TagsNo tags attached.
Attached Files

- Relationships

-  Notes
There are no notes attached to this issue.

- Issue History
Date Modified Username Field Change
2015-11-15 20:54 gerd New Issue
2017-02-23 16:43 doligez Category OCaml standard library => standard library
2017-04-13 13:07 doligez Status new => acknowledged


Copyright © 2000 - 2011 MantisBT Group
Powered by Mantis Bugtracker