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 1 year has passed since last update.

Go言語 チャネル

Posted at

チャネル

チャネルとは、平行実行されているGoroutineから値を受け渡す機能である。

Code

// ある数以上の素数を求める関数
func primeRoutine(targetLine int, primeChan chan int) {
	i := 0
	for {
		// 値のインクリメント
		i++
		// 素数チェック
		if checkPrime(i) && targetLine < i {
			// チャネルにデータ送信
			primeChan <- i //[キーポイント]
		}
	}
}

// メイン関数
func main() {

	// 求める素数の基準値
	targetLine := 100000

	// チャネルの作成
	primeChan := make(chan int)

	// ゴルーチンで素数を求める
	go primeRoutine(targetLine, primeChan)

	// チャネルからデータを受信
	primeResult := <-primeChan //[キーポイント]

	// 値の出力
	fmt.Println(primeResult)
}

Output Sample

~ $ go build -o prime main.go
~ $ ./prime
100003

GitHub

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?