mirror of
https://github.com/gopl-zh/gopl-zh.github.com.git
synced 2024-11-05 14:03:45 +00:00
32 lines
680 B
Go
32 lines
680 B
Go
// 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
|
|
}
|
|
|
|
//!-
|