Permalink
Cannot retrieve contributors at this time
Fetching contributors…
| // 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 | |
| } | |
| //!- |