mirror of
https://github.com/gopl-zh/gopl-zh.github.com.git
synced 2025-09-11 14:22:49 +00:00
good good study, day day up!
This commit is contained in:
31
vendor/gopl.io/ch9/bank1/bank.go
generated
vendored
Normal file
31
vendor/gopl.io/ch9/bank1/bank.go
generated
vendored
Normal file
@@ -0,0 +1,31 @@
|
||||
// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
|
||||
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
|
||||
|
||||
// See page 261.
|
||||
//!+
|
||||
|
||||
// Package bank provides a concurrency-safe bank with one account.
|
||||
package bank
|
||||
|
||||
var deposits = make(chan int) // send amount to deposit
|
||||
var balances = make(chan int) // receive balance
|
||||
|
||||
func Deposit(amount int) { deposits <- amount }
|
||||
func Balance() int { return <-balances }
|
||||
|
||||
func teller() {
|
||||
var balance int // balance is confined to teller goroutine
|
||||
for {
|
||||
select {
|
||||
case amount := <-deposits:
|
||||
balance += amount
|
||||
case balances <- balance:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func init() {
|
||||
go teller() // start the monitor goroutine
|
||||
}
|
||||
|
||||
//!-
|
36
vendor/gopl.io/ch9/bank1/bank_test.go
generated
vendored
Normal file
36
vendor/gopl.io/ch9/bank1/bank_test.go
generated
vendored
Normal file
@@ -0,0 +1,36 @@
|
||||
// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
|
||||
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
|
||||
|
||||
package bank_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"gopl.io/ch9/bank1"
|
||||
)
|
||||
|
||||
func TestBank(t *testing.T) {
|
||||
done := make(chan struct{})
|
||||
|
||||
// Alice
|
||||
go func() {
|
||||
bank.Deposit(200)
|
||||
fmt.Println("=", bank.Balance())
|
||||
done <- struct{}{}
|
||||
}()
|
||||
|
||||
// Bob
|
||||
go func() {
|
||||
bank.Deposit(100)
|
||||
done <- struct{}{}
|
||||
}()
|
||||
|
||||
// Wait for both transactions.
|
||||
<-done
|
||||
<-done
|
||||
|
||||
if got, want := bank.Balance(), 300; got != want {
|
||||
t.Errorf("Balance = %d, want %d", got, want)
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user