1 ! Copyright (C) 2005, 2010 Chris Double, Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: dlists deques threads sequences continuations namespaces
4 math quotations words kernel arrays assocs init system
5 concurrency.conditions accessors debugger debugger.threads
7 IN: concurrency.mailboxes
9 TUPLE: mailbox threads data ;
11 : <mailbox> ( -- mailbox )
16 : mailbox-empty? ( mailbox -- bool )
19 : mailbox-put ( obj mailbox -- )
21 [ threads>> notify-all ] bi yield ;
23 : wait-for-mailbox ( mailbox timeout -- )
24 [ threads>> ] dip "mailbox" wait ;
26 :: block-unless-pred ( ... mailbox timeout pred: ( ... message -- ... ? ) -- ... )
27 mailbox data>> pred dlist-any? [
28 mailbox timeout wait-for-mailbox
29 mailbox timeout pred block-unless-pred
30 ] unless ; inline recursive
32 : block-if-empty ( mailbox timeout -- mailbox )
34 2dup wait-for-mailbox block-if-empty
39 : mailbox-peek ( mailbox -- obj )
42 : mailbox-get-timeout ( mailbox timeout -- obj )
43 block-if-empty data>> pop-back ;
45 : mailbox-get ( mailbox -- obj )
46 f mailbox-get-timeout ;
48 : mailbox-get-all-timeout ( mailbox timeout -- array )
50 [ dup mailbox-empty? not ]
51 [ dup data>> pop-back ]
54 : mailbox-get-all ( mailbox -- array )
55 f mailbox-get-all-timeout ;
57 : while-mailbox-empty ( mailbox quot -- )
58 [ '[ _ mailbox-empty? ] ] dip while ; inline
60 : mailbox-get-timeout? ( mailbox timeout pred -- obj )
62 [ [ drop data>> ] dip delete-node-if ]
65 : mailbox-get? ( mailbox pred -- obj )
66 f swap mailbox-get-timeout? ; inline
68 : wait-for-close-timeout ( mailbox timeout -- )
70 [ 2drop ] [ 2dup wait-for-mailbox wait-for-close-timeout ] if ;
72 : wait-for-close ( mailbox -- )
73 f wait-for-close-timeout ;
75 TUPLE: linked-error error thread ;
77 M: linked-error error.
78 [ thread>> error-in-thread. ] [ error>> error. ] bi ;
80 C: <linked-error> linked-error
82 : ?linked ( message -- message )
83 dup linked-error? [ rethrow ] when ;
85 TUPLE: linked-thread < thread supervisor ;
87 M: linked-thread error-in-thread
88 [ <linked-error> ] [ supervisor>> ] bi mailbox-put ;
90 : <linked-thread> ( quot name mailbox -- thread' )
91 [ linked-thread new-thread ] dip >>supervisor ;
93 : spawn-linked-to ( quot name mailbox -- thread )
94 <linked-thread> [ (spawn) ] keep ;