guile-user
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Passing objects between threads


From: Chris Vine
Subject: Re: Passing objects between threads
Date: Sat, 10 Sep 2016 15:30:06 +0100

On Sat, 10 Sep 2016 11:37:55 +0200
Panicz Maciej Godek <address@hidden> wrote:
> Hi,
> is there any easy way to create a channel (queue) that could be used
> to communicate between threads? In particular, if the queue is empty,
> I would like the consumer to wait until something appears in it
> (pretty much like the channels in Clojure)

I haven't used Clojure channels, but what you describe is a traditional
blocking asynchronous queue.  Since guile has POSIX condition variables
they are trivial to make.  Here is one simple implementation, which
allows multiple writers and multiple readers.  async-queue-pop! blocks a
reader until something is available in the queue.  If there are
multiple readers, which reader awakens on any write is for the thread
scheduler. A loop is included in async-queue-pop! because POSIX
condition variables can spuriously wake up, so you have to test the
condition (whether the queue is empty or not) on any wake up before
returning.

You will find loads of literature and tutorials on this pattern, using
condition variables.


******************************************

(use-modules (srfi srfi-9)
             (ice-9 q)
             (ice-9 threads))

(define-record-type <async-queue>
  (_make-async-queue mutex cond q)
  async-queue?
  (mutex mutex-get)
  (cond cond-get)
  (q q-get))

   
(define (make-async-queue)
  (_make-async-queue (make-mutex)
                     (make-condition-variable)
                     (make-q)))

(define (async-queue-pop! a-q)
  (let ([mutex (mutex-get a-q)])
    (with-mutex mutex
      (let ([q (q-get a-q)])
        (let loop ()
          (if (q-empty? q)
              (begin
                (wait-condition-variable (cond-get a-q) mutex)
                (loop))
              (deq! q)))))))

(define (async-queue-push! a-q item)
  (with-mutex (mutex-get a-q)
    (enq! (q-get a-q) item))
  (signal-condition-variable (cond-get a-q)))




reply via email to

[Prev in Thread] Current Thread [Next in Thread]