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 3 years have passed since last update.

【Golang】ゴルーチン⑦チャネルのセレクト

Posted at

#【Golang】ゴルーチン⑦チャネルのセレクト
Golangの基礎学習〜Webアプリケーション作成までの学習を終えたので、復習を兼ねてまとめていく。 基礎〜応用まで。

package main 
//channelとselect
//selectを使った受信
//複数のチャネルを使った受信の分岐

//マルチプロセスのよう

import (
	"fmt"
	"time"
)

func goroutine1(c chan int) {
	//無限ループを避ける場合、条件を決め、close()する
	//下記、無限ループ
    for {
		c <- 100
		//1秒
		time.Sleep(1 * time.Second)
	}
}

func goroutine2(c chan string) {
    for {
		c <- "groutin2"
		time.Sleep(3 * time.Second)
	}
}

func main() {
	c1 := make(chan int)
	c2 := make(chan string)
 
	go goroutine1(c1)
	go goroutine2(c2)

	//無限ループする
	for {
		//channelで分岐できる
		select {
		//ch1からの受信
		case msg1 := <- c1:
			fmt.Println(msg1)
		//ch2からの受信
		case msg2 := <- c2:
			fmt.Println(msg2)
		}
	}
}
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?