gocui/_examples/goroutine.go

100 lines
1.5 KiB
Go
Raw Normal View History

// Copyright 2014 The gocui Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"log"
"sync"
"time"
"github.com/jroimartin/gocui"
)
const NumGoroutines = 10
var (
done = make(chan bool)
wg sync.WaitGroup
mu sync.Mutex // protects ctr
ctr = 0
)
func main() {
g := gocui.NewGui()
if err := g.Init(); err != nil {
log.Panicln(err)
}
defer g.Close()
g.SetLayout(layout)
if err := keybindings(g); err != nil {
log.Panicln(err)
}
for i := 0; i < NumGoroutines; i++ {
wg.Add(1)
go counter(g)
}
if err := g.MainLoop(); err != nil && err != gocui.ErrQuit {
log.Panicln(err)
}
wg.Wait()
}
func layout(g *gocui.Gui) error {
if v, err := g.SetView("ctr", 2, 2, 12, 4); err != nil {
if err != gocui.ErrUnknownView {
return err
}
fmt.Fprintln(v, "0")
}
return nil
}
func keybindings(g *gocui.Gui) error {
if err := g.SetKeybinding("", gocui.KeyCtrlC, gocui.ModNone, quit); err != nil {
return err
}
return nil
}
func quit(g *gocui.Gui, v *gocui.View) error {
for i := 0; i < NumGoroutines; i++ {
done <- true
}
return gocui.ErrQuit
}
func counter(g *gocui.Gui) {
defer wg.Done()
for {
select {
case <-done:
return
case <-time.After(500 * time.Millisecond):
g.Execute(func(g *gocui.Gui) error {
v, err := g.View("ctr")
if err != nil {
return err
}
mu.Lock()
n := ctr
ctr++
mu.Unlock()
v.Clear()
fmt.Fprintln(v, n)
return nil
})
}
}
}