45 lines
722 B
Go
45 lines
722 B
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"time"
|
|
)
|
|
|
|
func Saluda() {
|
|
fmt.Println("Hola desde un goroutine")
|
|
}
|
|
|
|
func imprimeNums(n int) {
|
|
for i := 0; i < n; i++ {
|
|
fmt.Println(i)
|
|
time.Sleep(time.Millisecond)
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
//go -> envia a otro hilo, las goroutinas son concurrentes, se ejecuta en paralelo
|
|
go Saluda()
|
|
time.Sleep(time.Second)
|
|
|
|
fmt.Println("fin del goroutine")
|
|
|
|
go imprimeNums(5)
|
|
go imprimeNums(5)
|
|
|
|
time.Sleep(time.Second)
|
|
|
|
// chan
|
|
ch := make(chan int)
|
|
go func() {
|
|
ch <- 64
|
|
}()
|
|
val := <-ch // espera hasta que se reciba un valor en el canal
|
|
fmt.Println(val)
|
|
|
|
ch2 := make(chan string, 2) // canal con bufer de 2 elementos
|
|
ch2 <- "hola"
|
|
ch2 <- "mundo"
|
|
fmt.Println(<-ch2)
|
|
fmt.Println(<-ch2)
|
|
}
|