-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfoobar.go
64 lines (56 loc) · 1.02 KB
/
foobar.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// https://leetcode.com/problems/print-foobar-alternately
// Non-channel solution
package main
import (
"sync"
)
type FooBar struct {
n int
MU sync.Mutex
b bool
cond *sync.Cond
}
func NewFooBar(n int) *FooBar {
fb := FooBar{n: n}
fbcond := sync.NewCond(&fb.MU)
fb.cond = fbcond
return &fb
}
func (fb *FooBar) Foo(printFoo func()) {
for i := 0; i < fb.n; i++ {
fb.MU.Lock()
for fb.b {
fb.cond.Wait()
}
// printFoo() outputs "foo". Do not change or remove this line.
printFoo()
fb.b = !fb.b
fb.MU.Unlock()
fb.cond.Signal()
}
}
func (fb *FooBar) Bar(printBar func()) {
for i := 0; i < fb.n; i++ {
fb.MU.Lock()
for !fb.b {
fb.cond.Wait()
}
// printBar() outputs "bar". Do not change or remove this line.
printBar()
fb.b = !fb.b
fb.MU.Unlock()
fb.cond.Signal()
}
}
// func printFoo() {
// fmt.Print("foo")
// }
// func printBar() {
// fmt.Print("bar")
// }
// func main() {
// fb := NewFooBar(5)
// go fb.Foo(printFoo)
// go fb.Bar(printBar)
// time.Sleep(time.Second * 1)
// }