package xapi-stdext-threads

  1. Overview
  2. Docs
Xapi's standard library extension, Threads

Install

Dune Dependency

Authors

Maintainers

Sources

xapi-stdext-4.21.0.tbz
sha256=427af021994ba881918c4c3a89d441fb000311d5e7c8e1ffcb1e239d899d7741
sha512=70c55e0fda2bf641cf1ccb4bcff8040a6a8f0e8a2d58a727492dedbe585a870a914bae83ca36917ed2e54fc978e70c4a95b454424b69065efae08035de8830f2

doc/src/xapi-stdext-threads/semaphore.ml.html

Source file semaphore.ml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
(*
 * Copyright (C) Citrix Systems Inc.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation; version 2.1 only. with the special
 * exception on linking described in file LICENSE.
 *
 * This program 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 Lesser General Public License for more details.
 *)

type t = {
  mutable n : int;
  m : Mutex.t;
  c : Condition.t;
}

let create n =
  if n <= 0 then
    invalid_arg (Printf.sprintf 
                   "Semaphore value must be positive, got %d" n);
  let m = Mutex.create ()
  and c = Condition.create () in
  { n; m; c; }

exception Inconsistent_state of string
let inconsistent_state fmt = Printf.ksprintf (fun msg ->
    raise (Inconsistent_state msg)) fmt

let acquire s k =
  if k <= 0 then
    invalid_arg (Printf.sprintf 
                   "Semaphore acquisition requires a positive value, got %d" k);
  Mutex.lock s.m;
  while s.n < k do
    Condition.wait s.c s.m;
  done;
  if not (s.n >= k) then
    inconsistent_state "Semaphore value cannot be smaller than %d, got %d" k s.n;
  s.n <- s.n - k;
  Condition.signal s.c;
  Mutex.unlock s.m

let release s k =
  if k <= 0 then
    invalid_arg (Printf.sprintf 
                   "Semaphore release requires a positive value, got %d" k);
  Mutex.lock s.m;
  s.n <- s.n + k;
  Condition.signal s.c;
  Mutex.unlock s.m

let execute_with_weight s k f =
  acquire s k;
  Xapi_stdext_pervasives.Pervasiveext.finally f
    (fun () -> release s k)

let execute s f =
  execute_with_weight s 1 f
OCaml

Innovation. Community. Security.