examples/example-6bb.rkt
#lang racket
;;;; Example 6bb - Selective Accepts with Internal State (using an explicit
;;; process type)

(require (planet williams/simulation/simulation))

;;; process type (lock-process (locked?))
;;;   locked? : boolean? = #f
(define-process-type lock-process
  ((locked? #f)))

;;; process (lock) : lock-process
;;; entry (lock) -> void?
;;; entry (unlock) -> void?
(define-process lock-process (lock)
  (let loop ()
    (select
      ((when (not (lock-process-locked? self))
         (accept caller (lock)))
       (set-lock-process-locked?! self #t))
      ((when (lock-process-locked? self)
         (accept caller (unlock)))
       (set-lock-process-locked?! self #f)))
    (loop)))

;;; process (p1 i a-lock)
;;;   i : exact-nonnegative-integer?
;;;   a-lock : process?
;;; This process uses the lock to protect its critical region, which just does a
;;; random wait in this case.
(define-process (p1 i a-lock)
  (printf "~a: process p1(~a) started.~n"
          (current-simulation-time) i)
  (call a-lock (lock))
  (printf "~a: process p1(~a) acquired lock.~n"
          (current-simulation-time) i)
  (wait (random-flat 0.0 10.0))
  (printf "~a: process p1(~a) releasing lock.~n"
          (current-simulation-time) i)
  (call a-lock (unlock)))

;;; (main n) -> void?
;;;   n : exact-nonnegative-integer?
;;; Creates the lock process and schedules n p1 processes that use the lock.
(define (main n)
  (with-new-simulation-environment
    (let ((a-lock (schedule #:now (lock))))
      (for ((i (in-range n)))
        (schedule #:at (random-flat 0.0 10.0) (p1 i a-lock)))
      (start-simulation))))

;;; Test with 10 p1 processes.
(main 10)