factor/core/threads/threads.factor

77 lines
1.7 KiB
Factor
Raw Normal View History

! Copyright (C) 2004, 2007 Slava Pestov.
2005-02-07 18:27:55 -05:00
! Copyright (C) 2005 Mackenzie Straight.
! See http://factorcode.org/license.txt for BSD license.
2004-08-20 21:26:25 -04:00
IN: threads
USING: arrays init hashtables io.backend kernel kernel.private
math namespaces queues sequences vectors io system sorting
continuations debugger ;
2004-08-20 21:26:25 -04:00
<PRIVATE
SYMBOL: sleep-queue
: sleep-time ( -- ms )
sleep-queue get-global
dup empty? [ drop 1000 ] [ first first millis [-] ] if ;
2005-08-23 15:50:32 -04:00
: run-queue ( -- queue ) \ run-queue get-global ;
2005-08-23 15:50:32 -04:00
: schedule-sleep ( ms continuation -- )
2array global [
sleep-queue [ swap add sort-keys ] change
] bind ;
: wake-up ( -- continuation )
global [
sleep-queue [ unclip second swap ] change
] bind ;
PRIVATE>
2006-08-15 21:23:05 -04:00
: schedule-thread ( continuation -- ) run-queue enque ;
2006-07-31 16:49:26 -04:00
2006-08-15 21:23:05 -04:00
: schedule-thread-with ( obj continuation -- )
2006-07-31 16:49:26 -04:00
2array schedule-thread ;
2005-08-23 15:50:32 -04:00
2006-07-31 16:49:26 -04:00
: stop ( -- )
walker-hook [
f swap continue-with
] [
run-queue deque dup array?
[ first2 continue-with ] [ continue ] if
] if* ;
2005-08-23 15:50:32 -04:00
2005-09-18 01:37:28 -04:00
: yield ( -- ) [ schedule-thread stop ] callcc0 ;
2005-08-23 15:50:32 -04:00
: sleep ( ms -- )
>fixnum millis + [ schedule-sleep stop ] callcc0 drop ;
2005-08-23 15:50:32 -04:00
: in-thread ( quot -- )
[
schedule-thread
2006-05-14 23:09:47 -04:00
V{ } set-catchstack
V{ } set-callstack
V{ } set-retainstack
[ print-error flush ] recover
stop
2005-09-18 01:37:28 -04:00
] callcc0 drop ;
2005-08-23 15:50:32 -04:00
<PRIVATE
: (idle-thread) ( slow? -- )
sleep-time dup zero?
[ wake-up schedule-thread 2drop ]
[ 0 ? io-multiplex ] if ;
2006-06-14 22:58:17 -04:00
: idle-thread ( -- )
run-queue queue-empty? (idle-thread) yield idle-thread ;
2005-08-24 00:30:07 -04:00
: init-threads ( -- )
2006-06-14 22:58:17 -04:00
<queue> \ run-queue set-global
f sleep-queue set-global
2006-07-17 15:08:38 -04:00
[ idle-thread ] in-thread ;
[ init-threads ] "threads" add-startup-hook
PRIVATE>