Last active
April 19, 2016 23:06
-
-
Save sgmac/00608e5a0ed16c45d877e1c580faac8e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Crear un programa que declare dos funciones anónimas. Una que cuente del 0 al 200 y otra que cuente de 200 a 0. | |
// Mostrar cada número con un identificador único para cada goroutine. | |
// Crear goroutines a partir de estas funciones. | |
// No permitir que main regrese hasta que ambas goroutines hayan terminado de correr. | |
// https://play.golang.org/p/wjhbcgFg-g | |
package main | |
// Agregar imports. | |
import ( | |
"fmt" | |
"runtime" | |
"sync" | |
) | |
func init() { | |
// Alojar un procesador para que el scheduler lo use. | |
runtime.GOMAXPROCS(1) | |
} | |
func main() { | |
// Declarar el wait group e iniciar el contador en 2. | |
var wg sync.WaitGroup | |
wg.Add(2) | |
// Declarar una función anónima y crear una goroutine. | |
go func(id, num int) { | |
// Declarar un loop que cuente del 200 al 0 e imprimir cada valor | |
for i := num; i > 0; i-- { | |
fmt.Printf("Goroutine ID: %d\t Number:%d\n", id, i) | |
} | |
// Decrementar la cuenta del wait group. | |
defer wg.Done() | |
}(1, 200) | |
// Declarar una función anónima y crear una goroutine. | |
go func(id, num int) { | |
// Declarar un loop que cuente del 0 al 200 e imprimir cada valor | |
for i := num; i < 200; i++ { | |
fmt.Printf("Goroutine ID: %d\t Number:%d\n", id, i) | |
} | |
// Decrementar la cuenta del wait group. | |
defer wg.Done() | |
}(2, 1) | |
// Esperar a que las goroutines terminen. | |
wg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment