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?

【Go入門】goroutine(ゴルーチン)って何?

Last updated at Posted at 2025-03-23

はじめに

Go言語には、並行処理をとても簡単に書ける機能があります。それが「goroutine(ゴルーチン)」です。
この記事では goroutine の基本から Playground 実行も含めて 初学者向けにまとめてみます。

🎯 goroutineとは?

goroutine(ゴルーチン)は、Goにおける「超軽量スレッド」のようなものです。

関数の前に go をつけるだけで、その関数が別の並行プロセスとして非同期に実行されます。

✅ 最小のgoroutine例

package main

import (
    "fmt"
    "time"
)

func main() {
    go fmt.Println("Hello from goroutine") // 非同期で実行

    time.Sleep(100 * time.Millisecond) // goroutineの実行を待つ
    fmt.Println("main done")
}

🔗 Playgroundで実行する

🧪 goroutineの典型例:並行して2つの処理を実行

package main

import (
    "fmt"
    "time"
)

func say(msg string) {
    for i := 0; i < 3; i++ {
        fmt.Println(msg)
        time.Sleep(500 * time.Millisecond)
    }
}

func main() {
    go say("world") // goroutineで非同期に
    say("hello")    // main routineで実行
}

🔗 Playgroundで実行する

⚠️ goroutineだけだと"早すぎる"問題

package main

import "fmt"

func main() {
    go fmt.Println("Hello from goroutine")
}

🔗 Playgroundで実行する

main() が終わると goroutine が終了前にプログラムが終わってしまうため、何も出力されません。

time.Sleep を使うとgoroutine の完了を「待つ」ことでちゃんと出力されます

package main

import (
    "fmt"
    "time"
)

func main() {
    go fmt.Println("Hello from goroutine")
    time.Sleep(time.Second)
}

🔗 Playgroundで実行する

完了したことを知るにはchan(チャネル)を使うこともあります。chanについてはこちらに記事を書きました🙇

📦 goroutineの特徴まとめ

特徴 内容
軽量 数千〜数万スレッド起動も可能
簡単 go 関数() だけでOK
自動管理 OSスレッドに比べて効率的
並行に動作 複数処理を同時に進行可能

🙋‍♀️ よくある疑問

Q. goroutineとスレッドは違うの?

A. OSレベルのスレッドではなく、Goランタイムが管理する軽量な「擬似スレッド」のようなもの。

🏁 まとめ

  • goroutine は Goの並行処理を支える超軽量スレッド
  • go 関数() の形で簡単に非同期処理が書ける
  • 同時に複数の処理を安全かつ効率よく走らせることができる
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?