gopl-zh.github.com/vendor/gopl.io/ch9/bank2/bank.go
2015-12-09 15:45:11 +08:00

29 lines
560 B
Go

// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
// See page 262.
// Package bank provides a concurrency-safe bank with one account.
package bank
//!+
var (
sema = make(chan struct{}, 1) // a binary semaphore guarding balance
balance int
)
func Deposit(amount int) {
sema <- struct{}{} // acquire token
balance = balance + amount
<-sema // release token
}
func Balance() int {
sema <- struct{}{} // acquire token
b := balance
<-sema // release token
return b
}
//!-