Professional Documents
Culture Documents
Concurrent and Systems Programming: Cgrep Channels
Concurrent and Systems Programming: Cgrep Channels
Concurrent and Systems Programming: Cgrep Channels
cgrep
channels
04/25/10 cgrep – 1
04/25/10 cgrep – 2
cgrep/cgrep.go
Grep
package cgrep; import ( "bufio"; "io"; "os"; "regexp" )
04/25/10 cgrep – 3
cgrep/cgrep.go
Source
func Source(out chan<- *string, r io.Reader, done chan<- os.Error) {
defer func() { out <- nil }() // upon return send nil to out
in := bufio.NewReader(r)
for {
switch body, er := in.ReadString('\n'); er {
case nil:
out <- &body
case os.EOF:
done <- nil
return
default:
done <- er
return
}
}
}
04/25/10 cgrep – 4
cgrep/cgrep.go
Sink
func Sink(out io.Writer, in <-chan *string, done chan<- os.Error) {
for body := <-in; body != nil; body = <-in {
if _, ew := io.WriteString(out, *body); ew != nil {
done <- ew
flush(in)
return
}
}
done <- nil
}
04/25/10 cgrep – 5
Channels
chan type // channel type
<- chan type // receive channel type (coerced)
chan <- type // send channel type
04/25/10 cgrep – 6
http://golang.org/doc/go_spec.html#Channel_types
http://golang.org/doc/go_spec.html#Communication_operators
http://www.cs.rit.edu/~ats/go-2009-3/code/cgrep2/
defer
defer function-call-expression
04/25/10 cgrep – 7
http://golang.org/doc/go_spec.html#Defer_statements
cgrep/main.go
match
package main
04/25/10 cgrep – 9
chan
$ chan
04/25/10 cgrep – 10
select
select {
case channel <- value : statement; ...
case <- channel : statement; ...
case lvalue = <- channel : statement; ...
case lvalue := <- channel : statement; ...
04/25/10 cgrep – 11
http://golang.org/doc/go_spec.html#Select_statements