factor/core/threads/threads.factor

72 lines
1.7 KiB
Factor
Raw Normal View History

2007-09-20 18:09:08 -04:00
! Copyright (C) 2004, 2007 Slava Pestov.
! Copyright (C) 2005 Mackenzie Straight.
! See http://factorcode.org/license.txt for BSD license.
IN: threads
USING: arrays init hashtables heaps io.backend kernel
kernel.private math namespaces sequences vectors io system
continuations debugger dlists ;
2007-09-20 18:09:08 -04:00
<PRIVATE
SYMBOL: sleep-queue
: sleep-time ( -- ms )
sleep-queue get-global dup heap-empty?
2007-11-05 12:35:44 -05:00
[ drop 1000 ] [ heap-peek nip millis [-] ] if ;
2007-09-20 18:09:08 -04:00
: run-queue ( -- queue ) \ run-queue get-global ;
2007-11-05 12:35:44 -05:00
: schedule-sleep ( continuation ms -- )
sleep-queue get-global heap-push ;
2007-09-20 18:09:08 -04:00
: wake-up ( -- continuation )
2007-11-05 12:35:44 -05:00
sleep-queue get-global heap-pop drop ;
2007-09-20 18:09:08 -04:00
PRIVATE>
2007-11-05 12:35:44 -05:00
: schedule-thread ( continuation -- )
run-queue push-front ;
2007-09-20 18:09:08 -04:00
: schedule-thread-with ( obj continuation -- )
2array schedule-thread ;
: stop ( -- )
walker-hook [
2008-01-13 13:29:04 -05:00
continue
2007-09-20 18:09:08 -04:00
] [
run-queue pop-back dup array?
2007-09-20 18:09:08 -04:00
[ first2 continue-with ] [ continue ] if
] if* ;
: yield ( -- ) [ schedule-thread stop ] callcc0 ;
: sleep ( ms -- )
2007-11-05 12:35:44 -05:00
>fixnum millis + [ schedule-sleep stop ] curry callcc0 ;
2007-09-20 18:09:08 -04:00
: in-thread ( quot -- )
[
>r schedule-thread r> [
V{ } set-catchstack
{ } set-retainstack
2007-10-06 13:34:34 -04:00
[ [ print-error ] recover stop ] call-clear
] 1 (throw)
2007-09-20 18:09:08 -04:00
] curry callcc0 ;
<PRIVATE
: (idle-thread) ( slow? -- )
sleep-time dup zero?
[ wake-up schedule-thread 2drop ]
[ 0 ? io-multiplex ] if ;
: idle-thread ( -- )
run-queue dlist-empty? (idle-thread) yield idle-thread ;
2007-09-20 18:09:08 -04:00
: init-threads ( -- )
<dlist> \ run-queue set-global
<min-heap> sleep-queue set-global
2007-09-20 18:09:08 -04:00
[ idle-thread ] in-thread ;
[ init-threads ] "threads" add-init-hook
PRIVATE>