Skip to content

Instantly share code, notes, and snippets.

@jooyunghan
Created May 12, 2012 15:48
Show Gist options
  • Save jooyunghan/2667234 to your computer and use it in GitHub Desktop.
Save jooyunghan/2667234 to your computer and use it in GitHub Desktop.
DevFestX Korea 2012 - Go concurrency idioms
package main
import (
"fmt"
"time"
)
type Data struct {
data string
rq1, rq2, rs1, rs2 chan bool
}
func NewData() *Data {
d := &Data{
data: "",
rq1: make(chan bool),
rq2: make(chan bool),
rs1: make(chan bool),
rs2: make(chan bool),
}
go d.handleRequest()
return d
}
func (d *Data) handleRequest() {
for {
select {
case <-d.rq1:
d.routine1()
d.rs1 <- true
case <-d.rq2:
d.routine2()
d.rs2 <- true
}
}
}
func (d *Data) print() {
fmt.Println(d.data)
}
func (d *Data) Routine1() {
d.rq1 <- true
<-d.rs1
}
func (d *Data) Routine2() {
d.rq2 <- true
<-d.rs2
}
func (d *Data) routine1() {
for i := 0; i < 20; i++ {
d.data += "1"
time.Sleep(20)
}
d.data += "\n"
}
func (d *Data) routine2() {
for i := 0; i < 20; i++ {
d.data += "2"
time.Sleep(2000)
}
d.data += "\n"
}
func main() {
d := NewData()
for i := 0; i < 20; i++ {
go d.Routine1()
go d.Routine2()
}
time.Sleep(2 * time.Second)
d.print()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment