Advertisement
Guest User

Untitled

a guest
Mar 15th, 2016
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 1.48 KB | None | 0 0
  1. open Core.Std
  2. open Async.Std
  3.  
  4. module Existential = struct
  5.  
  6.   type anytype = Any : 'a -> anytype
  7.  
  8. end;;
  9.  
  10. module Bundle = struct
  11.  
  12.   open Existential
  13.  
  14.   type t = anytype Ivar.t String.Table.t
  15.  
  16.   let create (keys : string list) =
  17.     let tbl = String.Table.create () in
  18.     List.iter keys ~f:(fun key ->
  19.       Hashtbl.set tbl ~key ~data:(Ivar.create ())
  20.     );
  21.     tbl
  22.   ;;
  23.  
  24.   let fill t key value =
  25.     let ivar = Hashtbl.find_exn t key in
  26.     Ivar.fill ivar (Existential.Any value)
  27.   ;;
  28.  
  29.   let wait_complete t =
  30.     let keys = Hashtbl.keys t in
  31.     List.map keys ~f:(fun key ->
  32.       Ivar.read (Hashtbl.find_exn t key)
  33.       >>| fun value ->
  34.       (key, value)
  35.     )
  36.     |> Deferred.all
  37.     >>| String.Table.of_alist_exn
  38.   ;;
  39.  
  40. end;;
  41.  
  42. type t =
  43.   { keys : string list
  44.   ; bundles : (int, Bundle.t) Hashtbl.t
  45.   ; processor : Existential.anytype String.Table.t -> unit
  46.   }
  47.  
  48. let create keys ~processor =
  49.   { keys
  50.   ; bundles = Hashtbl.create ~hashable:Int.hashable ()
  51.   ; processor
  52.   }
  53. ;;
  54.  
  55. let update t seq_id key value =
  56.   match Hashtbl.find t.bundles seq_id with
  57.   | Some bundle -> Bundle.fill bundle key value
  58.   | None        ->
  59.     let bundle = Bundle.create t.keys in
  60.     Hashtbl.set t.bundles ~key:seq_id ~data:bundle;
  61.     Bundle.fill bundle key value;
  62.     let process_bundle =
  63.       Bundle.wait_complete bundle
  64.       >>| fun table ->
  65.       Hashtbl.remove t.bundles seq_id;
  66.       t.processor table
  67.     in
  68.     Deferred.don't_wait_for(process_bundle)
  69. ;;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement