factor/extra/concurrency/semaphores/semaphores.factor

30 lines
878 B
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
continuations ;
2008-02-18 06:07:40 -05:00
IN: concurrency.semaphores
TUPLE: semaphore count threads ;
: <semaphore> ( n -- semaphore )
dup 0 < [ "Cannot have semaphore with negative count" throw ] when
2008-02-19 12:37:02 -05:00
<dlist> semaphore construct-boa ;
2008-02-18 06:07:40 -05:00
: wait-to-acquire ( semaphore timeout -- )
>r semaphore-threads r> "semaphore" wait ;
2008-02-18 06:07:40 -05:00
: acquire ( semaphore timeout -- )
2008-02-18 06:07:40 -05:00
dup semaphore-count zero? [
wait-to-acquire
] [
drop
2008-02-18 06:07:40 -05:00
dup semaphore-count 1- swap set-semaphore-count
] if ;
: release ( semaphore -- )
dup semaphore-count 1+ over set-semaphore-count
semaphore-threads notify-1 ;
: with-semaphore ( semaphore quot -- )
over acquire [ release ] curry [ ] cleanup ; inline