Instantly share code, notes, and snippets.

Embed
What would you like to do?
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