そもそもゴルーチンってなんやねんって話から
##goroutine##
並列処理してくれるやつ
使おうと思えば簡単に使えるけど
使いこなすってなると難しそうなやつ。
##やっていこう##
package main
import (
"time"
"fmt"
)
func goroutine1(){
for i:=0;i<5;i++ {
time.Sleep(time.Millisecond);
fmt.Print("goroutine");
}
}
func goroutine2(){
for i:=0;i<5;i++ {
time.Sleep(time.Millisecond);
fmt.Print("now");
}
}
func main(){
go goroutine1();
goroutine2();
}
###main関数から###
並列処理させたいやつの関数の前に go
を書けばやってくれる
なんとまぁ簡単なことでしょう
ちなみに表示はこんな感じになる
goroutine.go
now
goroutine
now
goroutine
goroutine
now
now
goroutine
goroutine
now
こんな感じになる
ここで_goroutine1_の **time.Sleep(time.Millisecond)**のtimeの前に100をかける
その後実行してみると面白いことが起きる
goroutine.go
now
now
now
now
now
###goroutineが消えた・・・###
なぜ消えたのか
並列処理のためにgoroutine1用のスレッドを生成する。
その後はスレッド内でgoroutine1を実行するので
main関数はgoroutine1のことを無視してgoroutine2へ
goroutine2は1msのスリープなので先に終了してしまう。
mainはgoroutine1がいたことなんて覚えてないのでこの結果になる。
##次回予告##
仲間はずれのgoroutine1を助けるにはどうしたらいいのか・・・
第二弾