Help us understand the problem. What is going on with this article?

goにおけるchannelの使い方

More than 1 year has passed since last update.

mainスレッドとgoroutine間で値を渡すにはchannelを使う

スクリーンショット 2019-03-12 21.39.01.png

1.make(chan 型)でchannelを作成
2. goroutineにchannelを持たせ、go goroutine(変数, channel)とする
3. 値は、「c <- numで受信、<-cで送信」(cはchannnel)
4. cに値が入るまで、<-cの次の行を実行させないことが可能

main.go
package main

import (
    "fmt"
)

func goroutine(s []string, c chan string) {
    var str string
    for _, v := range s {
        str += v
    }
    //c <- numでnumを受信
    //ここで受信するまで、mainスレッドでは次の行に行かない
    c <- str
}

func main() {
    s := []string{"Hello","World","!","Mr.","Ren" }
    //make(chan string)でstring型のchannelを作成
    c := make(chan string)
    //goroutineに渡す
    go goroutine(s, c)
    //xはsumが入ってくるまでずっと待ってる(ブロッキング)。入ってきたら次の行へ(sync.WaitGroupで待つ必要はない)
    //<-cで受信した値を送信
    x := <-c
    fmt.Println(x)
}

//処理結果
//HelloWorld!Mr.Ren
wjtnk
Ruby,PHP,Go,Docker,AWS
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした