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.

【川原のGo言語&Elixir奮闘記】#3 今日はGoで並行機能遊び

Last updated at Posted at 2019-09-26

Hello world私だよ。

前回でHello worldまで行けたよ。

今日はGoの並行機能で遊んでいくよ。

以下のプログラムを作るよ。

package main

import (
    "fmt"
    "time"
)

func readword(ch chan string) {
    fmt.Println("なんか入力して~")
    var word string
    fmt.Scanf("%s", &word)
    ch <- word
}

func timeout(t chan bool) {
    time.Sleep(10 * time.Second)
    t <- true
}

func main() {
    t := make(chan bool)
    go timeout(t)

    ch := make(chan string)
    go readword(ch)

    select {
    case word := <-ch:
        fmt.Println("承り~", word)
    case <-t:
        fmt.Println("はい、時間切れ~")
    }
}

####ここで重要なのは、"go"ルーチンと"select”っていう文だよ。

####両方の"go"ルーチンからの戻り値を"select”で受け付けているよ。

これを使うことによってプログラム上で非同期を表しているよ。

今日はGoの並行機能で遊んだよ。

最近、左目の上裏がちょっと痛いよ。

また来週。

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?