LoginSignup
0
0

More than 3 years have passed since last update.

【Golang】ゴルーチン②チャネル

Posted at

【Golang】ゴルーチン②チャネル

Golangの基礎学習〜Webアプリケーション作成までの学習を終えたので、復習を兼ねてまとめていく。 基礎〜応用まで。

package main

//channel
//スレッド同士のデータのやり取り

//複数チャネルを作って、処理することも可能

import (
    "fmt"
)

//sからcへ送信する処理
func goroutin1(s []int, c chan int) {
    sum := 0
    for _, v := range s {
        sum += v
        //都度、計算結果を出力
        fmt.Println(sum)

    }
    //全て処理が終わったら、channelに送信
    c <- sum
}

func main() {

    /*
        //var 変数 chan データ型
        var ch chan int

        //送信専用と受信専用の型を指定すると厳密になり、異なる場合、コンパイルエラーになる。
        //送受信に制限を設けない方がオススメ。
        //受信専用チャネル
        var ch1 <-chan int
        //送信専用チャネル
        var ch2 chan<- int
    */

    /*
        チャネルの特徴

        キュー(待ち行列)の性質を持つ。
        バッファサイズは格納できる領域。
        キューにはFIFO(先入先出し)という性質がある。

        チャネルに送信
        ch <- 1
        チャネルから受信
        i := <- ch
    */

    //スライス作成
    s := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    //channelを作成
    c := make(chan int)

    //並行で走らせる
    go goroutin1(s, c)
    go goroutin1(s, c)

    //channelからデータを受け取る
    //データが入るまで待ってくれる。
    //goroutine1でsumにデータが入ったらcに入り、xに送る
    x := <-c
    fmt.Println(x)
    y := <-c
    fmt.Println(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