Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

@wjtnk

goにおけるchannelの使い方

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
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
0
Help us understand the problem. What are the problem?