Skip to content

Instantly share code, notes, and snippets.

@thezerobit
Created November 6, 2012 22:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thezerobit/4028233 to your computer and use it in GitHub Desktop.
Save thezerobit/4028233 to your computer and use it in GitHub Desktop.
More complex green-threads / async example.
(ql:quickload "green-threads")
(ql:quickload "cl-async")
(defun f-http-client (url &rest rest)
(let ((http-future (green-threads:make-future)))
(apply #'cl-async:http-client
url
#'(lambda (status headers body)
(green-threads:complete-future
http-future status headers body nil))
#'(lambda (err)
(green-threads:complete-future
http-future nil nil nil err))
rest)
http-future))
(defun f-delay (&key time)
(let ((delay-future (green-threads:make-future)))
(funcall #'cl-async:delay
#'(lambda ()
(green-threads:complete-future
delay-future))
:time time)
delay-future))
(cl-async:start-event-loop
(lambda ()
;; The trick to having green threads run together is to call them from green thread
(green-threads:with-green-thread
;; Delay thread
(green-threads:with-green-thread
(format t "Starting 3 second delay.~%")
(green-threads:wait-on (f-delay :time 3.0))
(format t "Finished 3 second delay.~%"))
;; HTTP request thread
(green-threads:with-green-thread
(format t "Starting HTTP request.~%")
(green-threads:wait-on (f-http-client "http://blog.thezerobit.com/" :timeout 5))
(format t "Finished HTTP request.~%"))
;; Do some other things thread
(green-threads:with-green-thread
(format t "Doing other things in third thread...~%"))
)))
;; output:
;; Starting 3 second delay.
;; Starting HTTP request.
;; Doing other things in third thread...
;; Finished HTTP request.
;; Finished 3 second delay.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment