package main

import (
	"fmt"
	"math/rand"
	"sync"
	"time"
)

// just trying to simulate communication
// between goroutines, to test similar one in c with latches
var wg = new(sync.WaitGroup)
var tick = time.Tick(time.Second * 20)

func main() {

	wakeUpT1 := make(chan struct{}, 1)
	wakeUpT2 := make(chan struct{}, 1)
	closeCh := make(chan struct{}, 1)

	wg.Add(2)
	go thread(1, wakeUpT1, wakeUpT2, closeCh)
	go thread(2, wakeUpT2, wakeUpT1, closeCh)

	// boot strapping,
	wakeUpT1 <- struct{}{}

	wg.Wait()

}

func thread(id int, wakeMeUp, wakeHimup, closeCh chan struct{}) {
	defer wg.Done()

end:
	for {
		select {
		case <-wakeMeUp:
			t := time.Millisecond * time.Duration(rand.Intn(1000))
			fmt.Println(id, "woke up and doing work for:", t)
			<-time.Tick(t)
			wakeHimup <- struct{}{}
		case <-closeCh:
			fmt.Println("timeout, quitting", id)
			break end
		case <-tick:
			close(closeCh)
		}
	}
}
