good good study, day day up!

This commit is contained in:
chai2010
2015-12-09 15:45:11 +08:00
commit 1693baf5de
378 changed files with 23276 additions and 0 deletions

30
vendor/gopl.io/ch9/bank3/bank.go generated vendored Normal file
View File

@@ -0,0 +1,30 @@
// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
// See page 263.
// Package bank provides a concurrency-safe single-account bank.
package bank
//!+
import "sync"
var (
mu sync.Mutex // guards balance
balance int
)
func Deposit(amount int) {
mu.Lock()
balance = balance + amount
mu.Unlock()
}
func Balance() int {
mu.Lock()
b := balance
mu.Unlock()
return b
}
//!-

28
vendor/gopl.io/ch9/bank3/bank_test.go generated vendored Normal file
View File

@@ -0,0 +1,28 @@
// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
package bank_test
import (
"sync"
"testing"
"gopl.io/ch9/bank2"
)
func TestBank(t *testing.T) {
// Deposit [1..1000] concurrently.
var n sync.WaitGroup
for i := 1; i <= 1000; i++ {
n.Add(1)
go func(amount int) {
bank.Deposit(amount)
n.Done()
}(i)
}
n.Wait()
if got, want := bank.Balance(), (1000+1)*1000/2; got != want {
t.Errorf("Balance = %d, want %d", got, want)
}
}