Skip to content

Instantly share code, notes, and snippets.

@jakubkulhan
Created November 21, 2009 21:51
Show Gist options
  • Save jakubkulhan/240295 to your computer and use it in GitHub Desktop.
Save jakubkulhan/240295 to your computer and use it in GitHub Desktop.
package main
import (
"fmt";
"os";
"flag";
"pong";
)
var count = flag.Int("c", 3, "count of pings");
var help = flag.Bool("h", false, "show help");
func init() { flag.Parse(); }
func main() {
if *help {
flag.PrintDefaults();
return;
}
pong.New(*count, os.Stdout).Start(true);
fmt.Println("That's all folks!");
}
TARGET=$(notdir $(shell pwd))
MAGIC=$(shell (([ "$(GOARCH)" == "amd64" ] && echo 6) || ([ "$(GOARCH)" == "arm" ] && echo 5)) || echo 8)
all:
@for dir in `find * -type d`; do \
go=$$(find "$$dir" -maxdepth 1 -name "*.go"); \
if [ ! -z "$$go" ]; then \
echo "- $$dir: $$go"; \
$(MAGIC)g -I. -o _go_.8 $$go; \
rm -f $$dir.a; \
gopack grc $$dir.a _go_.8; \
fi \
done
@if [ -f 'main.go' ]; then \
$(MAGIC)g -I. -o _go_.8 main.go; \
$(MAGIC)l -o $(TARGET) _go_.8; \
fi
@rm -f _go_.8
clean:
@rm -f _go_.8 `find * -name "*.a"` $(TARGET)
package pong
import (
"fmt";
"io";
)
type Unit interface{}
type Pong struct {
n int;
out io.Writer;
ch chan chan Unit;
donech chan Unit;
}
const UNIT Unit = 0
func New(n int, out io.Writer) *Pong {
return &Pong{
n: n,
out: out,
ch: make(chan chan Unit),
donech: make(chan Unit)
};
}
func (p *Pong) Start(wait bool) (ok bool, donech chan Unit) {
go pong(p.ch, p.out);
go ping(p.n, p.ch, p.out, p.donech);
if wait {
<-p.donech;
return true, nil;
}
return true, p.donech;
}
func pong(ch chan chan Unit, out io.Writer) {
fmt.Fprintln(out, "pong started");
for {
if pingch := <-ch; pingch != nil {
fmt.Fprintln(out, "pong received ping");
pingch <- UNIT;
} else { break; }
}
fmt.Fprintln(out, "pong finished");
}
func ping(n int, ch chan chan Unit, out io.Writer, donech chan Unit) {
fmt.Fprintln(out, "ping started");
for ; n > 0; n-- {
pingch := make(chan Unit);
ch <- pingch;
<-pingch;
fmt.Fprintln(out, "ping received pong");
}
ch <- nil;
fmt.Fprintln(out, "ping finished");
donech <- UNIT;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment