From SICP:

Exercise 3.47. A semaphore (of size n) is a generalization of a mutex. Like a mutex, a semaphore supports acquire and release operations, but it is more general in that up to n processes can acquire it concurrently. Additional processes that attempt to acquire the semaphore must wait for release operations. Give implementations of semaphores

a. in terms of mutexes

(define (make-semaphore max)
  (let ((count 0)
        (the-mutex (make-mutex)))
    (define (increment)
      (set! count (+ count 1)))
    (define (decrement)
      (set! count (- count 1)))
    (define (has-room?) (> max count))
    (define (the-semaphore m)
      (cond ((eq? m 'acquire)
             (if (has-room?)
                 (the-mutex 'acquire)))
            ((eq? m 'release)
             (if (has-room?) (the-mutex 'release)))))

I wrote this answer and I'm hoping to find out if it is correct, and how it can be improved. Thank you for your time.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.