LennyBoyatzis
4/14/2018 - 10:13 AM

channels.go

package main

import (
	"fmt"
	"sync"
	"time"
)

func firstFunc(c1 chan string) {
	for {
		c1 <- "from 1"
		time.Sleep(time.Second * 2)
	}
}

func secondFunc(c2 chan string) {
	for {
		c2 <- "from 2"
		time.Sleep(time.Second * 3)
	}
}

func main() {
	c1 := make(chan string)
	c2 := make(chan string)
	wg := new(sync.WaitGroup)

	wg.Add(3)
	go firstFunc(c1)
	go secondFunc(c2)
	go func() {
		for {
			select {
			case msg1 := <-c1:
				fmt.Println(msg1)
			case msg2 := <-c2:
				fmt.Println(msg2)
			default:
				fmt.Println("Hello world")
				time.Sleep(time.Second * 3)
			}
		}
	}()
	wg.Wait()
}