viernes, 4 de noviembre de 2022

Ejemplo de uso de sync.WaitGroup en Go

 


En Go cuando queremos ejecutar una corutina luego que se ejecuten un conjunto de corutinas, podemos utilizar waitgroup. 

En el ejemplo se ordena un slice dividido en 4 partes en 4 corutinas diferentes y se espera a que terminen. Espero que les sirva. 

package main


import (

 "fmt"

 "strconv"

 "sort"

 "math/rand"

 "math"

 "sync"

)


func main() {

fmt.Println("enter quantity of integers")

var nroStr string

fmt.Scan(&nroStr)

nro, err := strconv.Atoi(nroStr)

if (err != nil) {

return;

}

wg := sync.WaitGroup{}

nros := make([]int, 0, nro)

for i := 0; i < nro; i++ {

nros = append(nros,rand.Intn(10*nro))

}

if nro > 4 {

quart := int(math.RoundToEven(float64(nro) / 4.0))

wg.Add(4)

for i:=0; i < 3; i++ {

start := (i * quart)

end := (((i + 1) * quart))

go sortNros(nros[start:end], &wg)

}

go sortNros(nros[(3 * quart) : nro], &wg)

} else {

wg.Add(1)

go sortNros(nros, &wg)

}

wg.Wait()

fmt.Println(nros)

}


func sortNros(nros []int, wg *sync.WaitGroup) {

sort.Ints(nros)

wg.Done()

}

    


No hay comentarios.:

Publicar un comentario