2020年5月15日金曜日

開発環境

入門Goプログラミング (Nathan Youngman(著)、Roger Peppé(著)、吉川 邦夫(監修, 翻訳)、翔泳社)のUNIT 7(並行プログラミング)、LESSON 31(競合状態)の練習問題-1の解答を求めてみる。

コード

package main

import (
 "fmt"
 "image"
 "time"
)

func worker() {
 pos := image.Point{X: 10, Y: 10}
 direction := image.Point{X: 1, Y: 0}
 d := time.Duration(time.Second / 2)
 next := time.After(d)
 for {
  select {
  case <-next:
   pos = pos.Add(direction)
   fmt.Println("current position is ", pos)

   next = time.After(d)
  }
 }
}
func main() {
 go worker()
 // 約9回移動、9行出力される
 time.Sleep(time.Second * 5)
}

入出力結果(Zsh、PowerShell、Terminal)

% go build positionworker.go
% ./positionworker          
current position is  (11,10)
current position is  (12,10)
current position is  (13,10)
current position is  (14,10)
current position is  (15,10)
current position is  (16,10)
current position is  (17,10)
current position is  (18,10)
current position is  (19,10)
% ./positionworker
current position is  (11,10)
current position is  (12,10)
current position is  (13,10)
current position is  (14,10)
current position is  (15,10)
current position is  (16,10)
current position is  (17,10)
current position is  (18,10)
current position is  (19,10)
%

0 コメント:

コメントを投稿