LoginSignup
0
2

More than 5 years have passed since last update.

goroutineで複数無限ループ処理を行う

Last updated at Posted at 2017-04-26

Go言語まだまだ勉強中です。
ご指摘いただけると嬉しいです。

やりたいこと

  • 無限ループ処理を複数goroutineで立ち上げて動かしたい
  • 死んだ処理を再帰的に立ち上げたい

mastodonのstreaming-apiでnotificationsを監視する処理を、
インスタンス(アカウント)の数だけ立ち上げるということをやって見て
goroutine理解度の低さから、そもそも無限ループしないなどハマってしまったので動作コードをアップしました。

簡易版動作コード

3つの無限ループgoroutineを立ち上げて一定時間ごとにprintlnする。
落ちた処理は再度立ち上げる。
テスト用に一定確率で処理を落とす。

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    // 処理対象(この数だけgoroutineを立てる)
    target := []int{1, 2, 3}

    inf := make(chan bool)

    go func(inf chan bool) {
        for i := range target {
            fmt.Println("goroutine up : ", i)
            go ctr(target[i], make(chan int))
        }
    }(inf)

    // 永遠に返ることがない
    <-inf
}

func ctr(n int, c chan int) {
    go loop(n, c)

    select {
    case <-c:
        fmt.Println("die and up:", n)
        ctr(n, c)
    }
}

func loop(no int, c chan int) {
    defer func() { c <- no }()
    for {
        fmt.Println("loop:", no)
        time.Sleep(1 * time.Second)
        if rand.Intn(10) == 1 {
            // テスト用に一定確率で落とす
            return
        }
    }
}
0
2
1

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
2