Skip to content

Channels in Arcueid

dido edited this page Jan 15, 2012 · 1 revision

(from http://www.arclanguage.org/item?id=1823)

 (chan)

creates a new communications channel. Any value can be read or written from it.

(<- channel)

returns the value that was last written to the channel, or blocks until a value is available to read from the channel, written by the <-= form.

(<-= channel val)

writes the value val to channel, or blocks if a value was already written that has not yet been read by another <- on channel.

To allow a thread to read or write to multiple channels, and to perform non-blocking communication, alt can be used:

(alt (<- channel) (...) (<-= value channel) (...) (...))

It's sort of like an if, with the even-numbered expressions restricted to being channel expressions that either read from or write to channels. The alt form will choose one of the channel expressions and execute the first one that it sees that will not block. It then executes the expression immediately following. Channel reads will bind the result of the read to it, making the value available to the succeeding expression. For example

(alt (<- chan)
     (prn "read " it " from channel")
     (<-= 2 chan2)
     (prn "wrote 2 to chan2 successfully")
     (prn "no channels available for non-blocking read or write"))

If we had instead written:

(alt (<- chan)
     (prn "read " it " from channel")
     (<-= 2 chan2)
     (prn "wrote 2 to chan2 successfully"))

Without the "else" expression, the alt operator would block the current thread until chan became readable or chan2 became writable.

Clone this wiki locally