 ! Copyright (C) 2005 Mackenzie Straight.
 ! See http://factorcode.org/license.txt for BSD license.
 IN: threads
-USING: arrays init hashtables io.backend kernel kernel.private
+USING: arrays init hashtables heaps io.backend kernel kernel.private
 math namespaces queues sequences vectors io system sorting
 continuations debugger ;
 


SYMBOL: sleep-queue

: sleep-time ( -- ms )
    sleep-queue get-global
    dup empty? [ drop 1000 ] [ first first millis [-] ] if ;

: run-queue ( -- queue ) \ run-queue get-global ;

: 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>



: init-threads ( -- )
    <queue> \ run-queue set-global
    <min-heap> sleep-queue set-global
    [ idle-thread ] in-thread ;

[ init-threads ] "threads" add-init-hook
PRIVATE>
