forked from torbiak/gopl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bank.go
41 lines (36 loc) · 868 Bytes
/
bank.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
// ex9.1 provides a concurrency-safe bank, with withdrawals.
package bank
type Withdrawal struct {
amount int
success chan bool
}
var deposits = make(chan int) // send amount to deposit
var balances = make(chan int) // receive balance
var withdrawals = make(chan Withdrawal)
func Deposit(amount int) { deposits <- amount }
func Balance() int { return <-balances }
func Withdraw(amount int) bool {
ch := make(chan bool)
withdrawals <- Withdrawal{amount, ch}
return <-ch
}
func teller() {
var balance int // balance is confined to teller goroutine
for {
select {
case amount := <-deposits:
balance += amount
case w := <-withdrawals:
if w.amount > balance {
w.success <- false
continue
}
balance -= w.amount
w.success <- true
case balances <- balance:
}
}
}
func init() {
go teller() // start the monitor goroutine
}