File: mvar.sml

package info (click to toggle)
smlsharp 4.2.0-1~exp1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 125,348 kB
  • sloc: ansic: 16,737; sh: 4,347; makefile: 2,228; java: 742; haskell: 493; ruby: 305; cpp: 284; pascal: 256; ml: 255; lisp: 141; asm: 97; sql: 74
file content (69 lines) | stat: -rw-r--r-- 1,660 bytes parent folder | download | duplicates (2)
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
63
64
65
66
67
68
69
(**
 * mvar.sml (copied from sample for myth)
 *
 * @copyright (C) 2021 SML# Development Team.
 * @author UENO Katsuhiro
 *)

structure MVar =
struct
  type 'a mvar =
       {mutex: Myth.mutex,
        cond: Myth.cond,
        content: 'a option ref}

  fun new () =
      let
        val mutex = Myth.Mutex.create ()
        val cond = Myth.Cond.create()
      in
        {mutex = mutex, cond = cond, content = ref NONE} : 'a mvar
      end

  fun waitUntil f (mvar as {mutex, cond, content}:'a mvar) =
      if f (!content) then ()
      else (Myth.Cond.wait (cond, mutex); waitUntil f mvar)

  fun put (mvar as {mutex, cond, content}:'a mvar, value) =
      (
        Myth.Mutex.lock mutex;
        waitUntil (not o isSome) mvar;
        content := SOME value;
        Myth.Cond.broadcast cond;
        Myth.Mutex.unlock mutex;
        ()
      )

  fun take (mvar as {mutex, cond, content}:'a mvar) =
      let
        val _ = Myth.Mutex.lock mutex
        val _ = waitUntil isSome mvar
        val ret = valOf (!content)
      in
        content := NONE;
        Myth.Cond.broadcast cond;
        Myth.Mutex.unlock mutex;
        ret
      end

  fun read (mvar as {mutex, cond, content}:'a mvar) =
      let
        val _ = Myth.Mutex.lock mutex
        val _ = waitUntil isSome mvar
        val ret = valOf (!content)
      in
        Myth.Mutex.unlock mutex;
        ret
      end

  fun isSome (mvar as {mutex, cond, content}:'a mvar) =
      let
        val _ = Myth.Mutex.lock mutex
        val ret = case !content of NONE => false | SOME _ => true
      in
        Myth.Cond.signal cond;
        Myth.Mutex.unlock mutex;
        ret
      end

end