Skip to content

Instantly share code, notes, and snippets.

@wari
Last active September 16, 2015 10:33
Show Gist options
  • Save wari/1e9ca4d462e2df0138f0 to your computer and use it in GitHub Desktop.
Save wari/1e9ca4d462e2df0138f0 to your computer and use it in GitHub Desktop.
// Package main provides a way to chope a place, once choped, other guys have
// to wait till it's available. chope is slang for reserved
package main
import (
"fmt"
"sync"
"time"
)
const (
waitLongLong int = iota
putTissue
)
type choperer struct {
Value string
chope chan struct{}
}
func (c *choperer) canChope() (int, chan struct{}) {
// Have not choped before
if c.chope == nil {
c.chope = make(chan struct{})
return putTissue, c.chope
}
return waitLongLong, c.chope
}
func main() {
// We got a table
table := &choperer{}
var wg sync.WaitGroup
// 10 people want the stuff on the table
wg.Add(10)
for i := 0; i < 10; i++ {
// Let all these people wait at the same time, and whoever is first get
// to chope.
go func(i int) {
fmt.Printf("Customer %d trying to chope\n", i)
chopeState, waitFirst := table.canChope()
if chopeState == waitLongLong {
<-waitFirst
}
if table.Value == "" {
// 5 seconds is supposed makan time
fmt.Printf("Customer %d got to chope first and eat\n", i)
time.Sleep(2 * time.Second)
table.Value = "Messy Table"
close(waitFirst) // Done eating
}
fmt.Printf("%d left because of %s\n", i, table.Value)
wg.Done()
}(i)
}
wg.Wait() // Wait for program to finish
}
@wari
Copy link
Author

wari commented Sep 16, 2015

See it working in action -> http://play.golang.org/p/lo02RbuyMa

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment