Skip to content

Instantly share code, notes, and snippets.

@Fuco1
Created August 28, 2015 21:57
Show Gist options
  • Save Fuco1/da28b92ea07f4f2f57ec to your computer and use it in GitHub Desktop.
Save Fuco1/da28b92ea07f4f2f57ec to your computer and use it in GitHub Desktop.
Cooperative threading with generators
;; Practical cooperative threading in emacs 25 using generators.
;; Requires generator.el library of emacs 25 (can be used stand-alone
;; on anything 24.3+)
;; Eval the next three forms. To start the computation, run the
;; timer.
(fset 'foo
(iter-lambda ()
(let ((i 0))
;; limit to 3 interupts for demo purposes
(while (<= i 3)
;; Send any event to emacs (hit a key combo) to interupt
;; the work being done. The work should be in granular
;; enough chunks to quickly terminate and not block the
;; event loop for long.
(while (not (input-pending-p))
;; Do work here. Open the messages buffer and see how
;; it accumulates nicely :)
(message "foo"))
(iter-yield (incf i))))))
(setq my-iterator (foo))
(defun my-job ()
(iter-next my-iterator)
(run-with-idle-timer 0 nil 'my-job))
;; then eval this
(run-with-idle-timer 0 nil 'my-job)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment