sábado, 5 de noviembre de 2022

Un ejemplo de uso de Go routines


Un ejemplo sencillo de Go routines, tenemos 2 Slices con diferentes números y queremos que se impriman en go routines diferentes y bueno, tengo que poner un time.Sleep(time.Second) para esperar que termine. 

Debería haber usado un sync.WaitGroup pero no lo hice, igual hay un ejemplo acá.


package main

import (

"fmt"

"time"

"math/rand"

)


func main(){

s1, s2 := []int{1,2,3}, []int{4,5,6}

fmt.Println("Let's Race !!!!!!!!!!!!\n")

go printElemOfIntSlice(s1, 100)

go printElemOfIntSlice(s2, 100)

time.Sleep(time.Second)

}


func printElemOfIntSlice(slice []int, velo int){

for _, val  := range slice{

fmt.Println(val)

duration := rand.Intn(velo)

time.Sleep(time.Duration(duration) * time.Millisecond)

}

}

No hay comentarios.:

Publicar un comentario