Bu örneğimizde eğer herhangi bir goroutine hata verirse, çalışan diğer goroutinleri iptal edeceğiz. Bu işlem için sync paketinin errgroup özelliğini kullanacağız. errgroup takım halinde çalışan goroutine gruplarında senkronizasyon, hata yayılımı ve Context iptal etme işlemleri için yaratılan bir özelliktir.


Örnek


Burada 3 tane goroutine çalıştıracağız. Eğer bunlardan herhangi biri kendi işini bitirmek için 80 milisaniyeden fazla gecikecekse, onu acelemiz olguğundan bir hata döndürmeye zorlayacağız. Bu durunda çalışan diğer goroutinlerde iptal edilecek. Aksi takdirde, hepsi normal olarak çalışacaklar.


package main

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

"golang.org/x/sync/errgroup"
)

func main() {
fmt.Println(">> START")

// Prevent picking up the same random number all the time for sleeping.
rand.Seed(time.Now().UnixNano())

goErrGroup, ctx := errgroup.WithContext(context.Background())

goErrGroup.Go(func() error {
return doSomething(ctx, 1)
})
goErrGroup.Go(func() error {
return doSomething(ctx, 2)
})
goErrGroup.Go(func() error {
return doSomething(ctx, 3)
})
goErrGroup.Go(func() error {
return doSomething(ctx, 4)
})

// Wait for the first error from any goroutine.
if err:= goErrGroup.Wait(); err != nil {
fmt.Println(err)
}

fmt.Println(">> FINISH")
}

func doSomething(ctx context.Context, id int) error {
fmt.Printf("STR: gorotinne %d\n", id)

// Pick a random number to simulate time it takes to finish the job.
delay := rand.Intn(100)
if delay > 80 {
return fmt.Errorf("FAIL: gorotinne %d: %dms", id, delay)
}
time.Sleep(time.Duration(delay) * time.Millisecond)

fmt.Printf("END: gorotinne %d\n", id)

return nil
}

Testler


Bu örnekte, tüm goroutinler yaptıklarını bitirmeyi başardılar.


>> START
STR: gorotinne 1
STR: gorotinne 2
STR: gorotinne 4
STR: gorotinne 3
END: gorotinne 3
END: gorotinne 1
END: gorotinne 4
END: gorotinne 2
>> FINISH

Bu örnekte, sadece 1 ve 4 numaralı goroutinler yaptıklarını bitirmeyi başardılar.


>> START
STR: gorotinne 1
STR: gorotinne 2
STR: gorotinne 3
STR: gorotinne 4
END: gorotinne 1
END: gorotinne 4
FAIL: gorotinne 2: 99ms
>> FINISH

Bu tam başlangıçta başarısız olduğundan, hiçbir goroutine yaptıklarını bitirmeyi başaramadı.


>> START
STR: gorotinne 1
STR: gorotinne 2
STR: gorotinne 3
STR: gorotinne 4
FAIL: gorotinne 1: 81ms
>> FINISH