開発環境
- macOS High Sierra - Apple (OS)
- Emacs (Text Editor)
- Go (プログラミング言語)
Introducing Go: Build Reliable, Scalable Programs (Caleb Doxsey (著)、O'Reilly Media)のChapter 10.(Concurrency)、Exercises(No. 1879)3.を取り組んでみる。
コード(Emacs)
package main
import (
"fmt"
"time"
)
var max int = 100000000
func send(c chan<- int) {
for i := 1; i <= max; i += 1 {
c <- i
}
}
func receive(secs int64, msg string, c <-chan int) {
for {
n := <-c
if n == max {
fmt.Println(msg, time.Now().Unix()-secs)
}
}
}
func main() {
// channel
c1 := make(chan int)
// buffered channel(a capacity of 20)
c2 := make(chan int, 20)
go send(c1)
go receive(time.Now().Unix(), "channel", c1)
go send(c2)
go receive(time.Now().Unix(), "buffered channel", c2)
var input string
fmt.Scanln(&input)
}
入出力結果(Terminal)
$ go run sample3.go buffered channel 7 channel 22 $
同期より非同期の方が速いことを確認できた。
0 コメント:
コメントを投稿