mirror of
https://github.com/gopl-zh/gopl-zh.github.com.git
synced 2024-11-19 21:03:43 +00:00
29 lines
560 B
Go
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
|
|
}
|
|
|
|
//!-
|