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" | |
"time" | |
) | |
type coisa struct { | |
nome string | |
cComecar chan bool | |
cParar chan bool | |
count int | |
} | |
func novaCoisa(nome string) *coisa { | |
c := coisa{ | |
nome: nome, | |
cComecar: make(chan bool), | |
cParar: make(chan bool), | |
} | |
fmt.Println("iniciando eventos de", nome) | |
go c.eventos() | |
fmt.Println("eventos iniciados") | |
return &c | |
} | |
func (c *coisa) parar() { | |
c.cParar <- true | |
} | |
func (c *coisa) comecar() { | |
c.cComecar <- true | |
} | |
func (c *coisa) eventos() { | |
for { | |
select { | |
case <-c.cComecar: | |
fmt.Println("começando", c.nome) | |
go c.tarefa() | |
default: | |
} | |
} | |
} | |
func (c *coisa) tarefa() { | |
for { | |
select { | |
case <-c.cParar: | |
fmt.Println("parando", c.nome) | |
return | |
default: | |
c.count++ | |
time.Sleep(1 * time.Second) | |
} | |
} | |
} | |
func main() { | |
coisa1 := novaCoisa("coisa1") | |
coisa2 := novaCoisa("coisa2") | |
coisa1.comecar() | |
coisa2.comecar() | |
time.Sleep(2 * time.Second) | |
fmt.Println("coisa1", coisa1.count) | |
fmt.Println("coisa2", coisa2.count) | |
coisa1.parar() | |
time.Sleep(6 * time.Second) | |
fmt.Println("coisa1", coisa1.count) | |
fmt.Println("coisa2", coisa2.count) | |
coisa1.comecar() | |
time.Sleep(6 * time.Second) | |
fmt.Println("coisa1", coisa1.count) | |
fmt.Println("coisa2", coisa2.count) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment