🖥

Go言語  — go文を書かなくても goroutine は走っている

2023/08/26に公開

go func の前に goroutine の数を出力すると 1 が返る。
(既にgoroutineが走っている)

package main

import "fmt"
import "runtime"
import "time"

func main() {
	// Print goroutine num
	fmt.Println(runtime.NumGoroutine()) // 1

	// run goroutine
	go func() {}()

	fmt.Println(runtime.NumGoroutine()) // 2

	time.Sleep(time.Second)
}

理解

  • goroutine とは元々 main の処理にも使われているものであり、必ず1個は走っている。
  • go 文で別の goroutine を走らせることが出来る。

ということだと思う。

きっかけ

A Tour of Go のこの文が気になって調べた。

The evaluation of f, x, y, and z happens in the current goroutine and the execution of f happens in the new goroutine.

環境

  • go version go1.10.3 darwin/amd64

Gist

参考

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

https://line.me/ti/g2/eEPltQ6Tzh3pYAZV8JXKZqc7PJ6L0rpm573dcQ

Twitter

https://twitter.com/YumaInaura

公開日時

2018-07-28

Discussion