/basis/concurrency/semaphores/semaphores.factor

http://github.com/abeaumont/factor · Factor · 38 lines · 26 code · 10 blank · 2 comment · 2 complexity · df5cab93c21f634c2294554fbbabf9eb MD5 · raw file

  1. ! Copyright (C) 2008 Slava Pestov.
  2. ! See http://factorcode.org/license.txt for BSD license.
  3. USING: dlists kernel threads math concurrency.conditions
  4. continuations accessors summary locals fry ;
  5. IN: concurrency.semaphores
  6. TUPLE: semaphore count threads ;
  7. ERROR: negative-count-semaphore ;
  8. M: negative-count-semaphore summary
  9. drop "Cannot have semaphore with negative count" ;
  10. : <semaphore> ( n -- semaphore )
  11. dup 0 < [ negative-count-semaphore ] when
  12. <dlist> semaphore boa ;
  13. : wait-to-acquire ( semaphore timeout -- )
  14. [ threads>> ] dip "semaphore" wait ;
  15. : acquire-timeout ( semaphore timeout -- )
  16. over count>> zero?
  17. [ dupd wait-to-acquire ] [ drop ] if
  18. [ 1 - ] change-count drop ;
  19. : acquire ( semaphore -- )
  20. f acquire-timeout ;
  21. : release ( semaphore -- )
  22. [ 1 + ] change-count
  23. threads>> notify-1 ;
  24. :: with-semaphore-timeout ( semaphore timeout quot -- )
  25. semaphore timeout acquire-timeout
  26. quot [ semaphore release ] [ ] cleanup ; inline
  27. : with-semaphore ( semaphore quot -- )
  28. swap dup acquire '[ _ release ] [ ] cleanup ; inline