factor/extra/channels/channels.factor

43 lines
1018 B
Factor
Raw Normal View History

2007-09-20 18:09:08 -04:00
! Copyright (C) 2007 Chris Double. All Rights Reserved.
! See http://factorcode.org/license.txt for BSD license.
!
! Channels - based on ideas from newsqueak
2008-02-21 00:13:22 -05:00
USING: kernel sequences sequences.lib threads continuations
random math ;
2007-09-20 18:09:08 -04:00
IN: channels
TUPLE: channel receivers senders ;
: <channel> ( -- channel )
V{ } clone V{ } clone channel construct-boa ;
GENERIC: to ( value channel -- )
GENERIC: from ( channel -- value )
<PRIVATE
: wait ( channel -- )
2008-02-21 00:13:22 -05:00
[ channel-senders push ] curry
"channel send" suspend drop ;
2007-09-20 18:09:08 -04:00
: (to) ( value receivers -- )
2008-02-18 10:08:59 -05:00
delete-random resume-with yield ;
2007-09-20 18:09:08 -04:00
: notify ( continuation channel -- channel )
[ channel-receivers push ] keep ;
2008-02-21 00:13:22 -05:00
: (from) ( senders -- )
delete-random resume ;
2007-09-20 18:09:08 -04:00
PRIVATE>
M: channel to ( value channel -- )
dup channel-receivers
dup empty? [ drop dup wait to ] [ nip (to) ] if ;
M: channel from ( channel -- value )
[
notify channel-senders
2008-02-21 00:13:22 -05:00
dup empty? [ drop ] [ (from) ] if
] curry "channel receive" suspend ;