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 1 year has passed since last update.

goroutineで並行処理のメモ

Posted at

goroutineを使ったときのメモです。

channelで待ち合わせせずgoroutineを使う場合の注意

mainのgoroutineが終了すると、他のgoroutineが走っていてもプログラムは終了してしまうので注意しよう。待ち合わせをしたい場合はchannelを使う。

main.go
package main

import (
	"fmt"
	"time"
)

func main() {
	go func() {
		fmt.Println("start goroutine")
		time.Sleep(3 * time.Second)
	}()

	// time.Sleep(4 * time.Second)
	fmt.Println("finished")
}

上記のコードを走らせた場合は以下のようになり、goroutineがそもそも開始されていないことがわかる。

$ go run main.go
finished

channelを使って待ち合わせした場合

main.go
package main

import (
	"fmt"
	"time"
)

func main() {
	done := make(chan bool)
	go func() {
		fmt.Println("start goroutine")
		time.Sleep(3 * time.Second)
		fmt.Println("finish goroutine")
		done <- true
	}()

	<-done
	fmt.Println("finished")
}

こちらの場合は以下のように出力される。

$ go run main.go
start goroutine
finish goroutine
finished
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?