factor/extra/coroutines/coroutines.factor

46 lines
1.1 KiB
Factor
Raw Normal View History

2007-09-20 18:09:08 -04:00
! Copyright (C) 2005 Chris Double, 2007 Clemens Hofreither.
! See http://factorcode.org/license.txt for BSD license.
2008-08-31 03:51:43 -04:00
USING: kernel hashtables namespaces continuations quotations
accessors ;
2007-09-20 18:09:08 -04:00
IN: coroutines
SYMBOL: current-coro
TUPLE: coroutine resumecc exitcc ;
: cocreate ( quot -- co )
coroutine new
2007-09-20 18:09:08 -04:00
dup current-coro associate
[ swapd , , \ bind ,
"Coroutine has terminated illegally." , \ throw ,
] [ ] make
2008-08-31 03:51:43 -04:00
>>resumecc ;
2007-09-20 18:09:08 -04:00
: coresume ( v co -- result )
[
2008-08-31 03:51:43 -04:00
>>exitcc
resumecc>> call
2007-09-20 18:09:08 -04:00
#! At this point, the coroutine quotation must have terminated
#! normally (without calling coyield or coterminate). This shouldn't happen.
f over
] callcc1 2nip ;
: coresume* ( v co -- ) coresume drop ; inline
: *coresume ( co -- result ) f swap coresume ; inline
: coyield ( v -- result )
current-coro get
[
[ continue-with ] curry
2008-08-31 03:51:43 -04:00
>>resumecc
exitcc>> continue-with
2007-09-20 18:09:08 -04:00
] callcc1 2nip ;
: coyield* ( v -- ) coyield drop ; inline
: *coyield ( -- v ) f coyield ; inline
: coterminate ( v -- )
current-coro get
2008-08-31 03:51:43 -04:00
[ ] >>resumecc
exitcc>> continue-with ;