2008-02-18 10:08:59 -05:00
|
|
|
! Copyright (C) 2008 Slava Pestov.
|
|
|
|
! See http://factorcode.org/license.txt for BSD license.
|
2008-02-18 17:20:18 -05:00
|
|
|
USING: dlists kernel threads math concurrency.conditions
|
|
|
|
continuations ;
|
2008-02-18 06:07:40 -05:00
|
|
|
IN: concurrency.semaphores
|
|
|
|
|
|
|
|
TUPLE: semaphore count threads ;
|
|
|
|
|
2008-02-18 17:20:18 -05:00
|
|
|
: <semaphore> ( n -- semaphore )
|
|
|
|
dup 0 < [ "Cannot have semaphore with negative count" throw ] when
|
2008-02-18 06:07:40 -05:00
|
|
|
0 <dlist> semaphore construct-boa ;
|
|
|
|
|
2008-02-18 17:20:18 -05:00
|
|
|
: wait-to-acquire ( semaphore timeout -- )
|
|
|
|
>r semaphore-threads r> wait ;
|
2008-02-18 06:07:40 -05:00
|
|
|
|
2008-02-18 17:20:18 -05:00
|
|
|
: acquire ( semaphore timeout -- )
|
2008-02-18 06:07:40 -05:00
|
|
|
dup semaphore-count zero? [
|
|
|
|
wait-to-acquire
|
|
|
|
] [
|
2008-02-18 17:20:18 -05:00
|
|
|
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 ;
|
2008-02-18 17:20:18 -05:00
|
|
|
|
|
|
|
: with-semaphore ( semaphore quot -- )
|
|
|
|
over acquire [ release ] curry [ ] cleanup ; inline
|