Last active
August 29, 2015 14:09
-
-
Save ciela/12d59edb82cbd7765171 to your computer and use it in GitHub Desktop.
goroutine周りのテストコード
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" | |
"sync" | |
"time" | |
"runtime" | |
) | |
func main(){ | |
fmt.Printf("Start: %v\n", runtime.NumGoroutine()) | |
var wg sync.WaitGroup | |
wg.Add(3) | |
finChan := make(chan bool) | |
errChan := make(chan error) | |
oneChan := make(chan int) | |
fiveChan := make(chan int) | |
tenChan := make(chan int) | |
go func() { | |
defer fmt.Println("OK!") | |
wg.Wait() | |
finChan <- true | |
}() | |
go func() { | |
defer wg.Done() | |
time.Sleep(1 * time.Second) | |
if false { | |
errChan <- fmt.Errorf("error!") | |
return | |
} | |
fmt.Println("One") | |
oneChan <- 1 | |
}() | |
go func() { | |
defer wg.Done() | |
time.Sleep(5 * time.Second) | |
if false { | |
errChan <- fmt.Errorf("error!") | |
return | |
} | |
fmt.Println("Five") | |
fiveChan <- 5 | |
}() | |
go func() { | |
defer wg.Done() | |
time.Sleep(10 * time.Second) | |
if false { | |
errChan <- fmt.Errorf("error!") | |
return | |
} | |
fmt.Println("Ten") | |
tenChan <- 10 | |
}() | |
var err error | |
EVENT: | |
for { | |
select { | |
case <-finChan: | |
close(errChan) | |
break EVENT | |
case err = <-errChan: | |
break EVENT | |
case one := <-oneChan: | |
fmt.Println(one) | |
case five := <-fiveChan: | |
fmt.Println(five) | |
case ten := <-tenChan: | |
fmt.Println(ten) | |
} | |
} | |
if err != nil { | |
fmt.Println(err.Error()) | |
} | |
time.Sleep(10 * time.Second) | |
fmt.Printf("End: %v", runtime.NumGoroutine()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment