Library zoo_std.semaphore__code

Require Import zoo.prelude.
Require Import zoo.language.typeclasses.
Require Import zoo.language.notations.
Require Import zoo_std.condition.
Require Import zoo_std.mutex.
Require Import zoo.options.

Notation "'semaphoreู mutex'" := (
  in_type "zoo_std.semaphore.t" 0
)(in custom zoo_field
).
Notation "'semaphoreู condition'" := (
  in_type "zoo_std.semaphore.t" 1
)(in custom zoo_field
).
Notation "'semaphoreู count'" := (
  in_type "zoo_std.semaphore.t" 2
)(in custom zoo_field
).

Definition semaphoreู create : val :=
  ๐—ณ๐˜‚๐—ป "cap" โ†’
    { mutexู create (), conditionู create (), "cap" - 1 }.

Definition semaphoreู try_lock : val :=
  ๐—ณ๐˜‚๐—ป "t" โ†’
    mutexู protect "t".{semaphoreู mutex}
      (๐—ณ๐˜‚๐—ป โŽฝ โ†’
         ๐—น๐—ฒ๐˜ "cnt" = "t".{semaphoreู count} ๐—ถ๐—ป
         ๐—ถ๐—ณ 0 < "cnt" ๐˜๐—ต๐—ฒ๐—ป (
           "t" <-{semaphoreู count} "cnt" - 1 โฎ
           true
         ) ๐—ฒ๐—น๐˜€๐—ฒ (
           false
         )).

Definition semaphoreู lock : val :=
  ๐—ณ๐˜‚๐—ป "t" โ†’
    mutexู protect "t".{semaphoreู mutex}
      (๐—ณ๐˜‚๐—ป โŽฝ โ†’
         conditionู wait_until
           "t".{semaphoreู condition}
           "t".{semaphoreู mutex}
           (๐—ณ๐˜‚๐—ป โŽฝ โ†’ 0 < "t".{semaphoreู count}) โฎ
         "t" <-{semaphoreู count} "t".{semaphoreู count} - 1).

Definition semaphoreู unlock : val :=
  ๐—ณ๐˜‚๐—ป "t" โ†’
    mutexู protect
      "t".{semaphoreู mutex}
      (๐—ณ๐˜‚๐—ป โŽฝ โ†’
         "t" <-{semaphoreู count} "t".{semaphoreู count} + 1) โฎ
    conditionู notify "t".{semaphoreู condition}.