2018年8月30日木曜日

開発環境

  • 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)1.を取り組んでみる。

コード(Emacs)

package main

import (
 "fmt"
 "time"
)

func f(c chan<- string) {
 for {
  c <- "form 1"
  time.Sleep(time.Second * 2)
 }
}
func g(c chan<- string) {
 for {
  c <- "form 2"
  time.Sleep(time.Second * 3)
 }
}
func h(c1 <-chan string, c2 <-chan string) {
 for i := 1; ; i += 1 {
  fmt.Print(i, ": ")
  select {
  case msg1 := <-c1:
   fmt.Println(msg1)
  case msg2 := <-c2:
   fmt.Println(msg2)
  }
 }
}
func main() {
 c1 := make(chan string)
 c2 := make(chan string)

 go f(c1)
 go g(c2)
 go h(c1, c2)
 var input string
 fmt.Scanln(&input)
}

入出力結果(Terminal)

$ go run sample1.go
1: form 1
2: form 2
3: form 1
4: form 2
5: form 1
6: form 2
7: form 1
8: form 1
9: form 2
10: form 1
11: form 2
12: form 1
13: form 1
14: form 2
15: form 1
16: form 2
17: form 1
18: form 1
19: form 2
20: form 1
21: 
$

0 コメント:

コメントを投稿

関連コンテンツ