Last active
March 7, 2017 07:50
-
-
Save danield137/1803d0b606a3376c7260f67b65c61af8 to your computer and use it in GitHub Desktop.
Basic channels example in go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
func main() { | |
t := NewTest() | |
// call methods on separate goroutines | |
go t.C() | |
go t.B() | |
go t.A() | |
// allow code to run | |
time.Sleep(1 * time.Second) | |
} | |
type Test struct { | |
foo chan string | |
bar chan string | |
} | |
func NewTest() *Test { | |
// init channels | |
return &Test{ | |
foo: make(chan string), | |
bar: make(chan string), | |
} | |
} | |
func (t *Test) A() { | |
fmt.Println("func A") | |
t.foo <- "a" | |
t.foo <- "b" | |
t.foo <- "c" | |
t.foo <- "d" | |
t.foo <- "e" | |
t.foo <- "f" | |
} | |
func (t *Test) B() { | |
str := "" | |
fmt.Println("func B") | |
// run for ever | |
for { | |
select | |
{ | |
// read item from channel | |
case s := <-t.foo: | |
{ | |
str += s | |
if len(str)%3 == 0 { | |
t.bar <- str | |
str = "" | |
} | |
} | |
} | |
} | |
} | |
func (t *Test) C() { | |
fmt.Println("func C") | |
for { | |
select | |
{ | |
case s := <-t.bar: | |
fmt.Println(s) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment