]> gitweb.factorcode.org Git - factor.git/blob - basis/channels/channels.factor
9b8c418634183d6cae0c4b9093e4461874354f22
[factor.git] / basis / 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 threads continuations
6 random math accessors random ;
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     [ 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     [ receivers>> push ] keep ;
28
29 : (from) ( senders -- )
30     delete-random resume ;
31
32 PRIVATE>
33
34 M: channel to ( value channel -- )
35     dup receivers>>
36     [ dup wait to ] [ nip (to) ] if-empty ;
37
38 M: channel from ( channel -- value )
39     [
40         notify senders>>
41         [ (from) ] unless-empty
42     ] curry "channel receive" suspend ;