1
2

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.

俺もgolangでゴルーチン触ってみたい!!

Last updated at Posted at 2019-06-05

そもそもゴルーチンってなんやねんって話から
##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を助けるにはどうしたらいいのか・・・
第二弾

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?