Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a golang solution for the Queue problem from section 3.8 #18

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions LittleBookOfSemaphores/chapter3/queue/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# 3.8 Queue

For example, imagine that threads represent ballroom dancers and that two
kinds of dancers, leaders and followers, wait in two queues before entering the
dance floor. When a leader arrives, it checks to see if there is a follower waiting.
If so, they can both proceed. Otherwise it waits.

Similarly, when a follower arrives, it checks for a leader and either proceeds
or waits, accordingly.

Puzzle: write code for leaders and followers that enforces these constraints.
60 changes: 60 additions & 0 deletions LittleBookOfSemaphores/chapter3/queue/go/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package main

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

type leader struct{ id int }
type follower struct{ id int }

func main() {
lq := make(chan *leader)
fq := make(chan *follower)

dance := func(l *leader, f *follower) {
fmt.Printf("Leader (%d) is dancing with Follower (%d)\n", l.id, f.id)
}

triggerLeader := func(id int) {
leaderArrival(id, lq, fq, dance)
}
triggerFollower := func(id int) {
followerArrival(id, lq, fq, dance)
}

go trigger("Leader", triggerLeader)
go trigger("Follower", triggerFollower)

time.Sleep(time.Duration(15) * time.Second)
}

func trigger(name string, event func(int)) {
for i := 0; ; i++ {
sleep := rand.Intn(999) + 1
time.Sleep(time.Duration(sleep) * time.Millisecond)
fmt.Printf("Triggering (%s)\n", name)
go event(i)
}
}

func leaderArrival(id int, lq chan *leader, fq chan *follower, dance func(*leader, *follower)) {
l := &leader{id: id}
select {
case f := <-fq:
dance(l, f)
default:
lq <- l
}
}

func followerArrival(id int, lq chan *leader, fq chan *follower, dance func(*leader, *follower)) {
f := &follower{id: id}
select {
case l := <-lq:
dance(l, f)
default:
fq <- f
}
}