[gambit-list] Question on "buffering:" option for vector-port

Marc Feeley feeley at iro.umontreal.ca
Tue Jan 24 22:15:06 EST 2012


On 2012-01-22, at 12:09 PM, Meng Zhang wrote:

> I expect the reading option may block the thread with "buffering: #f".
> 
> For example:
> (let ((chan (open-vector '(buffering: #f))))
>   (thread-start!
>     (make-thread
>       (lambda ()
>         (write "Value" chan)
>         (pp "Write done"))))
>   (thread-start!
>     (make-thread
>       (lambda ()
>         (thread-sleep! 1)
>         (pp "Start reading")
>         (pp (read chan)))))
>   (thread-sleep! 5))
> 
> My expectation:
> Outputs:
> "Start reading"
> "Write done" or "Value", in any order.
> 
> Result for 4.6.3, osx 10.6.7:
> Outputs:
> "Write done"
> "Start reading"
> "Value"
> 
> Obviously, the "read" option doesn't block the spawned thread even "buffering" is set to #f.
> Did I misunderstand it?
> 

When you set buffering to #t, you are telling the runtime system that it is allowed to buffer the data that is output.  The runtime system may drain the buffers at anytime it wishes.  In other words setting buffering to #f guarantees that the data is not buffered, but there are no guarantees when buffering is #t.

Here's another example derived from yours:

(let ((chan (open-vector '(buffering: #t))))

  (thread-start!
    (make-thread
      (lambda ()
        (let loop ()
          (thread-sleep! .2)
          (write "Value" chan)
          ;;(force-output chan)
          (pp "Write done")
          (loop)))))

  (thread-start!
    (make-thread
      (lambda ()
        (let loop ()
          (pp "Start reading")
          (pp (list 'got (read chan)))
          (loop)))))

  (thread-sleep! 5))

As it is, the second thread will read from the vector port in bursts.  What is perhaps surprising is that the second thread starts waiting for data to read, then the first thread writes the first data, and the second thread immediately reads it.  That's because the first buffer is allocated lazily when the first data is written.  On the following writes by the first thread, the second thread will wait until the buffer is full.  To get synchronous writes and reads, either buffering should be set to #f, or the (force-output chan) should be uncommented.

Marc




More information about the Gambit-list mailing list