Skip to content

Instantly share code, notes, and snippets.

@gerep
Created May 22, 2020
Embed
What would you like to do?
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