--PROG progs/sieve.go /Send/ /^}/
The function "Generate" sends the sequence 2, 3, 4, 5, ... to its
-argument channel, "ch", using the binary send operator "-<".
+argument channel, "ch", using the binary communications operator "<-".
Channels block, so if there's no recipient for the the value on "ch",
the send operation will wait until one becomes available.
The "Filter" function has three arguments: an input channel, an output
channel, and a prime number. It copies values from the input to the
-output, discarding anything divisible by the prime. The unary prefix
+output, discarding anything divisible by the prime. The unary communications
operator "<-" (receive) retrieves the next value on the channel.
--PROG progs/sieve.go /Copy/ /^}/
-
The generator and filters execute concurrently. Go has
its own model of process/threads/light-weight processes/coroutines,
so to avoid notational confusion we'll call concurrently executing
listed by its cases can proceed. If all are blocked, it waits until one can proceed; if
multiple can proceed, it chooses one at random. In this instance, the "select" allows
the server to honor requests until it receives a quit message, at which point it
-returns, terminating its execution. (The language doesn't yet allow the ":="
-syntax in "select" statements, although it might one day. Also, observe the use
-of the binary, infix form of the receive operator.)
+returns, terminating its execution.
All that's left is to strobe the "quit" channel
func Run(op *BinOp, request *Request) {
result := op(request.a, request.b);
- request.replyc -< result;
+ request.replyc <- result;
}
func Server(op *BinOp, service *chan *Request) {
req.a = i;
req.b = i + N;
req.replyc = new(chan int);
- adder -< req;
+ adder <- req;
}
for i := N-1; i >= 0; i-- { // doesn't matter what order
if <-reqs[i].replyc != N + 2*i {
func Run(op *BinOp, request *Request) {
result := op(request.a, request.b);
- request.replyc -< result;
+ request.replyc <- result;
}
func Server(op *BinOp, service *chan *Request, quit *chan bool) {
for {
- var request *Request;
select {
- case request <- service:
+ case request := <-service:
go Run(op, request); // don't wait for it
case <-quit:
return;
req.a = i;
req.b = i + N;
req.replyc = new(chan int);
- adder -< req;
+ adder <- req;
}
for i := N-1; i >= 0; i-- { // doesn't matter what order
if <-reqs[i].replyc != N + 2*i {
print("fail at ", i, "\n");
}
}
- quit -< true;
+ quit <- true;
}
// Send the sequence 2, 3, 4, ... to channel 'ch'.
func Generate(ch *chan int) {
for i := 2; ; i++ {
- ch -< i // Send 'i' to channel 'ch'.
+ ch <- i // Send 'i' to channel 'ch'.
}
}
for {
i := <-in // Receive value of new variable 'i' from 'in'.
if i % prime != 0 {
- out -< i // Send 'i' to channel 'out'.
+ out <- i // Send 'i' to channel 'out'.
}
}
}