]> gitweb.factorcode.org Git - factor.git/blob - extra/channels/channels.factor
Merge branch 'master' of git://factorcode.org/git/factor
[factor.git] / extra / channels / channels.factor
1 ! Copyright (C) 2007 Chris Double. All Rights Reserved.
2 ! See http://factorcode.org/license.txt for BSD license.
3 !
4 ! Channels - based on ideas from newsqueak
5 USING: kernel sequences sequences.lib threads continuations
6 random math ;
7 IN: channels
8
9 TUPLE: channel receivers senders ;
10
11 : <channel> ( -- channel )
12     V{ } clone V{ } clone channel boa ;
13
14 GENERIC: to ( value channel -- )
15 GENERIC: from ( channel -- value )
16
17 <PRIVATE
18
19 : wait ( channel -- )
20     [ channel-senders push ] curry
21     "channel send" suspend drop ;
22
23 : (to) ( value receivers -- )
24     delete-random resume-with yield ;
25
26 : notify ( continuation channel -- channel )
27     [ channel-receivers push ] keep ;
28
29 : (from) ( senders -- )
30     delete-random resume ;
31
32 PRIVATE>
33
34 M: channel to ( value channel -- )
35     dup channel-receivers
36     dup empty? [ drop dup wait to ] [ nip (to) ] if ;
37
38 M: channel from ( channel -- value )
39     [
40         notify channel-senders
41         dup empty? [ drop ] [ (from) ] if
42     ] curry "channel receive" suspend ;