! See http://factorcode.org/license.txt for BSD license.
USING: accessors assocs boxes calendar
combinators.short-circuit fry heaps init kernel math.order
-namespaces quotations threads math monotonic-clock ;
+namespaces quotations threads math system ;
IN: alarms
TUPLE: alarm
: <alarm> ( quot start interval -- alarm )
alarm new
swap dup [ normalize-argument ] when >>interval
- swap dup [ normalize-argument monotonic-count + ] when >>start
+ swap dup [ normalize-argument nano-count + ] when >>start
swap >>quot
<box> >>entry ;
[ start>> ] dip <= ;
: reschedule-alarm ( alarm -- )
- dup interval>> monotonic-count + >>start register-alarm ;
+ dup interval>> nano-count + >>start register-alarm ;
: call-alarm ( alarm -- )
[ entry>> box> drop ]
] if ;
: trigger-alarms ( alarms -- )
- monotonic-count (trigger-alarms) ;
+ nano-count (trigger-alarms) ;
: next-alarm ( alarms -- timestamp/f )
dup heap-empty? [ drop f ] [
heap-peek drop start>>
- monotonic-count swap -
- nanoseconds hence
+ nano-count swap -
] if ;
: alarm-thread-loop ( -- )
: unix-time>timestamp ( seconds -- timestamp )
seconds unix-1970 time+ ;
-M: timestamp sleep-until timestamp>micros sleep-until ;
-
-M: duration sleep hence sleep-until ;
+M: duration sleep duration>nanoseconds nano-count + sleep-until ;
{
{ [ os unix? ] [ "calendar.unix" ] }
{
{ [ run-queue deque-empty? not ] [ 0 ] }
{ [ sleep-queue heap-empty? ] [ f ] }
- [ sleep-queue heap-peek nip system-micros [-] ]
+ [ sleep-queue heap-peek nip nano-count [-] ]
} cond ;
DEFER: stop
: expire-sleep? ( heap -- ? )
dup heap-empty?
- [ drop f ] [ heap-peek nip system-micros <= ] if ;
+ [ drop f ] [ heap-peek nip nano-count <= ] if ;
: expire-sleep ( thread -- )
f >>sleep-entry resume ;
GENERIC: sleep ( dt -- )
M: real sleep
- system-micros + >integer sleep-until ;
+ >integer 1000 *
+ nano-count + sleep-until ;
: interrupt ( thread -- )
dup state>> [