0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【A Tour of Go】Concurrency/Channels (2/11)

Posted at

A Tour of Go の Exercise を実施したときのメモ。

  • goroutine の呼び出し順と x、y が一致しない
    • 実行結果が-5 17 12になる
  • sleep を入れると goroutine の呼び出し順どおりになる
    • 実行結果が17 -5 12になる
  • スレッドなので実行順は不定となる。
channels.go
package main

import "fmt"
import _"time"

func sum(s []int, c chan int) {
	sum := 0
	for _, v := range s {
		sum += v
	}
	c <- sum // send sum to c
}

func main() {
	s := []int{7, 2, 8, -9, 4, 0}

	c := make(chan int)
	go sum(s[:len(s)/2], c)
	//time.Sleep(1 * time.Second)
	go sum(s[len(s)/2:], c)
	x, y:= <-c, <-c // receive from c

	fmt.Println(x, y, x+y)
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?