gopl-zh.github.com/vendor/gopl.io/ch9/bank2/bank.go
github-actions[bot] ca571eb691 deploy: 06a1bdf735
2022-08-04 06:59:33 +00: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
}
//!-