factor/basis/concurrency/semaphores/semaphores.factor

39 lines
1.1 KiB
Factor
Raw Normal View History

2008-02-18 10:08:59 -05:00
! Copyright (C) 2008 Slava Pestov.
! See http://factorcode.org/license.txt for BSD license.
USING: dlists kernel threads math concurrency.conditions
2008-11-30 19:28:15 -05:00
continuations accessors summary locals fry ;
2008-02-18 06:07:40 -05:00
IN: concurrency.semaphores
TUPLE: semaphore count threads ;
2008-08-29 02:00:39 -04:00
ERROR: negative-count-semaphore ;
M: negative-count-semaphore summary
drop "Cannot have semaphore with negative count" ;
: <semaphore> ( n -- semaphore )
2008-08-29 02:00:39 -04:00
dup 0 < [ negative-count-semaphore ] when
<dlist> semaphore boa ;
2008-02-18 06:07:40 -05:00
: wait-to-acquire ( semaphore timeout -- )
2008-08-29 02:00:39 -04:00
[ threads>> ] dip "semaphore" wait ;
2008-02-18 06:07:40 -05:00
: acquire-timeout ( semaphore timeout -- )
2008-08-29 02:00:39 -04:00
over count>> zero?
[ dupd wait-to-acquire ] [ drop ] if
2008-08-29 02:00:39 -04:00
[ 1- ] change-count drop ;
: acquire ( semaphore -- )
f acquire-timeout ;
2008-02-18 06:07:40 -05:00
: release ( semaphore -- )
2008-08-29 02:00:39 -04:00
[ 1+ ] change-count
threads>> notify-1 ;
2008-11-30 19:28:15 -05:00
:: with-semaphore-timeout ( semaphore timeout quot -- )
semaphore timeout acquire-timeout
quot [ semaphore release ] [ ] cleanup ; inline
: with-semaphore ( semaphore quot -- )
2008-11-30 19:28:15 -05:00
swap dup acquire '[ _ release ] [ ] cleanup ; inline