lisp threading example

October 23, 2010

today I wanted to experiment with threads in lisp (sbcl, in particular).

here is a trivial example of how to access a shared resource (a closure, keeping a list of integers), from a set of *nt* threads.

(use-package :sb-thread)

;; number of threads
(defparameter *nt* 10)

;; threads
(defvar *threads* '())

;; mutex to use with shared resource accessed by the threads
(defvar *a-mutex* (make-mutex :name "acc-lock"))

;; shared closure accessed by the threads
(let ((x '()))
  (defun acc (v)
    (with-mutex (*a-mutex*)
                (push v x)))
  (defun get-acc ()
    x))

;; print the shared resource
(print (get-acc))

;; wait for all the threads to return
(mapcar #'join-thread
        ;; run the threads
        (loop :for i :below *nt*   
              ;; bind i to x so it is local to the thread
              :collect (let ((x i))
                        (make-thread #'(lambda ()
                                         ;; body of the thread
                                         (sleep (random 2))
                                         (acc x))
                                     :name x))))

;; print the shared resource
(print (get-acc))

it can’t get much simpler than that…

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: