Last active
August 29, 2015 14:02
-
-
Save bolilla/f2e3f377bd9a327223d8 to your computer and use it in GitHub Desktop.
GoPadawan Concurrencia Contador Sincronizado con Canales
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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