No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Multiplexación con Select y Case

27/30
Recursos

Aportes 5

Preguntas 0

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

otro ejemplo de select y case: https://tour.golang.org/concurrency/5
Case

Code:

package main

import (
	"fmt"
	"time"
)

func doSomething(i time.Duration, c chan<- int, param int) {
	time.Sleep(i)
	c <- param
}

func main() {
	c1 := make(chan int)
	c2 := make(chan int)

	d1 := 4 * time.Second
	d2 := 2 * time.Second

	go doSomething(d1, c1, 1)
	go doSomething(d2, c2, 2)

	for i := 0; i < 2; i++ {
		select {
		case channelMsg1 := <-c1:
			fmt.Println(channelMsg1)
		case channelMsg2 := <-c2:
			fmt.Println(channelMsg2)
		}
	}
}

package main

import (
	"fmt"
	"time"
)

func doSomething(i time.Duration, c chan<- int, param int) {
	time.Sleep(i)
	c <- param
}

func main() {
	c1 := make(chan int)
	c2 := make(chan int)

	d1 := 4 * time.Second
	d2 := 2 * time.Second

	go doSomething(d1, c1, 1)
	go doSomething(d2, c2, 2)

	/* fmt.Println("Waiting for the first result")
	fmt.Println(<-c1)
	fmt.Println("Waiting for the second result")
	fmt.Println(<-c2) */

	for i := 0; i < 2; i++ {
		select {
		case res := <-c1:
			fmt.Println("Received", res, "from c1")
		case res := <-c2:
			fmt.Println("Received", res, "from c2")
		}
	}

}

Code

package main

import (
	"fmt"
	"math/rand"
	"time"
)

func doSomething(i time.Duration, c chan<- int, param int) {
	time.Sleep(i)
	c <- param
}

func main() {
	c1 := make(chan int)
	c2 := make(chan int)

	// generate random number
	rand.Seed(time.Now().UnixNano())
	d1 := time.Duration(rand.Intn(10)) * time.Second
	d2 := time.Duration(rand.Intn(10)) * time.Second

	go doSomething(d1, c1, 1)
	go doSomething(d2, c2, 2)

	/* fmt.Println("Waiting for the first result")
	fmt.Println(<-c1)
	fmt.Println("Waiting for the second result")
	fmt.Println(<-c2) */

	for i := 0; i < 2; i++ {
		// wait for the completion of tasks
		select {
		case res := <-c1:
			fmt.Println("Received", res, "from c1 after", d1)
		case res := <-c2:
			fmt.Println("Received", res, "from c2 after", d2)
		}
	}

}

En Go también tenemos el default case como los tradicionales switch-case 🔥

https://go.dev/tour/concurrency/6