Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bolilla/f2e3f377bd9a327223d8 to your computer and use it in GitHub Desktop.
Save bolilla/f2e3f377bd9a327223d8 to your computer and use it in GitHub Desktop.
GoPadawan Concurrencia Contador Sincronizado con Canales
package main
import "fmt"
type contador struct {
l, s chan int //leer y sumar
v int //valor
}
func (c *contador) leer() int {
return <-c.l
}
func (c *contador) sumar(in int) {
c.s <- in
}
func (c *contador) matar() {
close(c.l)
close(c.s)
}
func newContador() *contador {
res := new(contador)
res.l = make(chan int)
res.s = make(chan int)
go res.gestionar()
return res
}
func (c *contador) gestionar() {
for {
select {
case i, abierto := <-c.s:
if !abierto {
break
}
c.v += i
case c.l <- c.v:
}
}
}
func main() {
c := newContador()
fmt.Println("Contador", c.leer())
c.sumar(42)
fmt.Println("Contador", c.leer())
c.matar()
fmt.Println("Contador", c.leer())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment