Skip to content

Instantly share code, notes, and snippets.

@alexlatam
Created February 14, 2023 13:25
Show Gist options
  • Save alexlatam/ef8f3dc703f61ee394a31055a8fa3e8e to your computer and use it in GitHub Desktop.
Save alexlatam/ef8f3dc703f61ee394a31055a8fa3e8e to your computer and use it in GitHub Desktop.
Example of concurrencie using GO(Golang)
package main
import (
"fmt"
"runtime" // Este paquete permite trabajar con las Go rutinas
"sync" // Permite crear sincronizar las rutinas de Go
)
// Variable que permite crear grupos de rutinas
var wg sync.WaitGroup
func main() {
// Obtenemos el sistema operativo de la maquina host
fmt.Println("OS\t\t", runtime.GOOS)
// Obtenemos la arquitectura del sistema
fmt.Println("ARCH\t\t", runtime.GOARCH)
// Obtenemos la cantidad de nucleos o hilos que contiene el procesador
fmt.Println("CPUs\t\t", runtime.NumCPU())
// Obtenemos el numero de rutinas que se estan ejecutando en el script.
fmt.Println("Goroutines\t", runtime.NumGoroutine())
// Incrementamos el contador de rutinas en uno(+1)
// Se podria incrementar en dos o mas rutinas. EJ: wg.Add(n)
// En este ejemplo solo estamos incrementando en una rutina
wg.Add(1)
// Lanzamos la ejecucion de la funcion hacia una nueva rutina
go foo()
// Se ejecuta esta funcion
bar()
fmt.Println("CPUs\t\t", runtime.NumCPU())
fmt.Println("Goroutines\t", runtime.NumGoroutine())
// Le indicamos a la funcion main que debe esperar hasta que todas las rutinas se ejecuten(finalicen)
// Esta funcion se puede colocar en cualquier lugar, se coloca aqui por el ejemplo
wg.Wait()
}
func foo() {
for i := 0; i < 10; i++ {
fmt.Println("foo:", i)
}
// Indicamos que la actual rutina ha terminado. Esto reduce el contador de rutinas en uno(-1)
wg.Done()
}
func bar() {
for i := 0; i < 10; i++ {
fmt.Println("bar:", i)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment