summaryrefslogtreecommitdiff
path: root/fibers
diff options
context:
space:
mode:
Diffstat (limited to 'fibers')
-rw-r--r--fibers/internal.scm12
-rw-r--r--fibers/timers.scm51
2 files changed, 56 insertions, 7 deletions
diff --git a/fibers/internal.scm b/fibers/internal.scm
index f03ebb1..ce83d58 100644
--- a/fibers/internal.scm
+++ b/fibers/internal.scm
@@ -434,10 +434,8 @@ from a finalizer thread."
(add-fdes-finalizer! fd (lambda (fd) (finalize-fd sched fd)))
(epoll-add! (scheduler-epfd sched) fd (logior events EPOLLONESHOT))))))
-(define (add-timer! sched thunk seconds)
- (let ((waketime (+ (get-internal-real-time)
- (inexact->exact
- (round (* seconds internal-time-units-per-second))))))
- (set-scheduler-timers!
- sched
- (psq-set (scheduler-timers sched) (cons waketime thunk) waketime))))
+(define (add-timer! sched thunk expiry)
+ (set-scheduler-timers! sched
+ (psq-set (scheduler-timers sched)
+ (cons expiry thunk)
+ expiry)))
diff --git a/fibers/timers.scm b/fibers/timers.scm
new file mode 100644
index 0000000..14c9787
--- /dev/null
+++ b/fibers/timers.scm
@@ -0,0 +1,51 @@
+;; Fibers: cooperative, event-driven user-space threads.
+
+;;;; Copyright (C) 2016 Free Software Foundation, Inc.
+;;;;
+;;;; This library is free software; you can redistribute it and/or
+;;;; modify it under the terms of the GNU Lesser General Public
+;;;; License as published by the Free Software Foundation; either
+;;;; version 3 of the License, or (at your option) any later version.
+;;;;
+;;;; This library is distributed in the hope that it will be useful,
+;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+;;;; Lesser General Public License for more details.
+;;;;
+;;;; You should have received a copy of the GNU Lesser General Public
+;;;; License along with this library; if not, write to the Free Software
+;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+;;;;
+
+(define-module (fibers timers)
+ #:use-module (fibers internal)
+ #:use-module (fibers operations)
+ #:use-module (ice-9 atomic)
+ #:use-module (ice-9 match)
+ #:export (wait-operation
+ timer-operation)
+ #:replace (sleep))
+
+(define (timer-operation expiry)
+ (make-base-operation #f
+ (lambda ()
+ (and (< expiry (get-internal-real-time))
+ values))
+ (lambda (flag fiber wrap-fn)
+ (define (maybe-resume-fiber)
+ (match (atomic-box-compare-and-swap! flag 'W 'S)
+ ('W (resume-fiber fiber (or wrap-fn values)))
+ ('C (maybe-resume-fiber))
+ ('S (values))))
+ (add-timer! (fiber-scheduler fiber)
+ maybe-resume-fiber
+ expiry))))
+
+(define (wait-operation seconds)
+ (timer-operation
+ (+ (get-internal-real-time)
+ (inexact->exact
+ (round (* seconds internal-time-units-per-second))))))
+
+(define (sleep seconds)
+ (perform-operation (wait-operation seconds)))