Skip to content

Instantly share code, notes, and snippets.

@ivan-avalos
Created May 29, 2020 02:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivan-avalos/4e77996f0a61e3c95dfdf4b63ad80f54 to your computer and use it in GitHub Desktop.
Save ivan-avalos/4e77996f0a61e3c95dfdf4b63ad80f54 to your computer and use it in GitHub Desktop.
Mutex en Chicken Scheme con SRFI-18
;; mutex.scm
;; Copyright (C) 2020 Iván Alejandro Ávalos Díaz
;;
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;;
;; 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 General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <https://www.gnu.org/licenses/>.
(require-extension srfi-13)
(require-extension srfi-18)
(require-extension srfi-28)
(define-constant n-thread 20)
(define-constant sleep-thread 0.2)
(define-constant MAX 2)
(define ans 0)
(define finished 0)
(define mtx (make-mutex))
(define threads (make-vector n-thread))
(define hello
(lambda ()
(mutex-lock! mtx)
(print* (format "Thread: ~a | " (thread-name (current-thread))))
(let loop ((i 0))
(when (< i MAX)
(set! ans (add1 ans))
(loop (add1 i))))
(print (format "Count: ~a" ans))
(thread-sleep! sleep-thread)
(set! finished (add1 finished))
(mutex-unlock! mtx)))
(print (format "Threads: ~a | Sleep: ~a | Value: ~a" n-thread sleep-thread MAX))
(thread-sleep! sleep-thread)
(let loop ((i 0))
(when (< i n-thread)
(vector-set! threads i (make-thread hello i))
(loop (add1 i))))
(let loop ((i 0))
(when (< i n-thread)
(thread-start! (vector-ref threads i))
(loop (add1 i))))
(let loop ()
(when (< finished n-thread)
(loop)))
(print (format "Actual Count: ~a | Expected Count: ~a"
ans (* MAX n-thread)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment