Open vkorbes opened 3 years ago
https://play.golang.org/p/v22RZp1ZUeU
package main
import (
"fmt"
"runtime"
)
/* - Crie um programa que lance 10 goroutines onde cada uma envia 10 números a um canal;
- Tire estes números do canal e demonstre-os. */
func main() {
canal := make(chan int)
go send(canal)
receive(canal)
}
func send(c chan int) {
for i := 1; i < 10; i++ {
go func() {
fmt.Println("Number of runnable goroutines: ", runtime.NumGoroutine())
for l := 1; l < 11; l++ {
c <- l
}
}()
}
}
func receive(rc chan int) {
func() {
for e := 1; e < 91; e++ {
fmt.Println(<-rc)
}
close(rc)
}()
}
`package main
import ( "fmt" "sync" )
var wg sync.WaitGroup
func main() {
communicationChannel := make(chan int)
numberOfGoRoutines := 10
wg.Add(numberOfGoRoutines)
go engine(numberOfGoRoutines, communicationChannel)
go readMessagesFromChannel(communicationChannel)
wg.Wait()
}
func engine(nGRoutines int, comChannel chan<- int) { numberOfMessages := 10 for i := 0; i < nGRoutines; i++ {
go func(numberOfMessages int) {
for msg := 0; msg < numberOfMessages; msg++ {
fmt.Println("ADDING MESSAGE", msg, "TO CHANNEL")
comChannel <- msg
}
wg.Done()
}(numberOfMessages)
}
}
func readMessagesFromChannel(channel chan int) { for v := range channel { fmt.Println("MESSAGE RECEIVED ", v) } // close(channel) wg.Done()
} `
package main
import (
"fmt"
"sync"
)
func main() {
c := make(chan int)
f := muitoGougro(10, c)
impr(f)
}
func muitoGougro(n int, c chan int) <-chan int {
var wg sync.WaitGroup
for i := 0; i < n; i++ {
wg.Add(1)
go func() {
for j := 0; j < n; j++ {
c <- j
}
wg.Done()
}()
}
return c
}
func impr(f <-chan int) {
for i := 0; i < 100; i++ {
fmt.Println(<-f)
}
}
Obrigado, Ellen, muito últil suas aulas. Um livro meu para compartilhar se achar importante
package main
import (
"fmt"
// "runtime"
"sync"
)
var wg sync.WaitGroup
func main() {
// Crie um canal com buffer de capacidade 10 para permitir o envio sem recebimento imediato.
c := make(chan int, 10)
go launchTenGoFuncs(c)
readChannel(c)
// readChannel2(c)
}
func launchTenGoFuncs(c chan int) {
wg.Add(10)
for i := 0; i < 10; i++ {
go func() {
for j := i * 10; j < i*10+10; j++ {
c <- j // Enviar para o canal
}
wg.Done()
}()
}
wg.Wait()
close(c)
}
func readChannel(c chan int) {
for {
select {
case v, ok := <-c:
if ok {
fmt.Println(v)
} else {
fmt.Println("Não há mais valores em c ->", v, "ok -> ", ok)
return
}
}
}
}
func readChannel2(c chan int) {
fmt.Println("-----------------------------READ CHANNEL 2--------------------------------")
for v := range c {
fmt.Println(v)
}
}
Exercício: Capítulo 22, Exercício 7 (Nível: 10)
Use esta thread para compartilhar sua solução, discutir o exercício com os colegas e pedir ajuda caso tenha dificuldades!