“canal de Golang” Réponses codées

canal de Golang

// When we send data into the channel using a GoRoutine, 
// it will be blocked until the data is consumed by another GoRoutine.

// When we receive data from channel using a GoRoutine, 
// it will be blocked until the data is available in the channel.

func main() {
	runIncrement()
}

func runIncrement() {
	channel := make(chan string)

	go increment(channel)
	time.Sleep(1 * time.Second)

	for msg := range channel {
		fmt.Println(msg)
	}
}

func increment(channel chan string) {
	for i := 0; i < 3; i++ {
		channel <- "Hello Wordl"
	}
	time.Sleep(1 * time.Second)
	close(channel)
}

func runCounter() {
	channel := make(chan string)
	wg := sync.WaitGroup{}

	wg.Add(1)
	go counter(channel, &wg)

	for msg := range channel {
		fmt.Println(msg)
	}
	wg.Wait()
}

func counter(channel chan string, wg *sync.WaitGroup) {
	for i := 0; i < 3; i++ {
		channel <- "Hello world"
	}
	wg.Done()
	close(channel)
}
Restu Wahyu Saputra

Golang fait Chan

ch <- v    // Send v to channel ch.
v := <-ch  // Receive from ch, and
           // assign value to v.
Bright Booby

Réponses similaires à “canal de Golang”

Questions similaires à “canal de Golang”

Parcourir les réponses de code populaires par langue

Parcourir d'autres langages de code