I wonder if anyone has given a great deal of thought to this. I myself lean towards doing things the way languages such as Limbo and Erlang do it, in the style of C.A.R. Hoare's CSP. I would propose adding a communication channel data type, along with operators for reading and writing to them. (newchan) creates a new communication channel. Any value can be sent across it. (<- channel) returns the value that has been put on the channel, or blocks the thread that does it until some other thread writes to the channel. (<-= value channel) writes the value to the channel. The writer will block unless there is some other thread reading on that 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 operator 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. 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. The spawn operator evaluates its argument in a new thread of control. Its value is a thread object, which can be manipulated in various ways, e.g. with functions such as threadkill (which forces the thread to stop immediately) and threadjoin (which waits for the thread to finish executing; its value then becomes the value of the thread argument). These operators and conventions are mostly borrowed from the Limbo programming language under Inferno. Any suggestions for how to improve these idioms are very much welcome. For more on the Limbo language: http://www.vitanuova.com/inferno/papers/limbo.html |