mirror of
https://github.com/golang/go.git
synced 2025-05-05 23:53:05 +00:00
Fix concurrency example compilation, plus extra example
parent
1e67b1cba4
commit
6a941f07bd
@ -831,13 +831,21 @@ Here is an example of using a manager function to control access to a
|
|||||||
single value.
|
single value.
|
||||||
|
|
||||||
```go
|
```go
|
||||||
type Cmd struct { Get bool; Val int }
|
type Cmd struct {
|
||||||
|
Get bool
|
||||||
|
Val int
|
||||||
|
}
|
||||||
|
|
||||||
func Manager(ch chan Cmd) {
|
func Manager(ch chan Cmd) {
|
||||||
val := 0
|
val := 0
|
||||||
for {
|
for {
|
||||||
c := <-ch
|
c := <-ch
|
||||||
if c.Get { c.Val = val; ch <- c }
|
if c.Get {
|
||||||
else { val = c.Val }
|
c.Val = val
|
||||||
|
ch <- c
|
||||||
|
} else {
|
||||||
|
val = c.Val
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@ -850,13 +858,21 @@ instead.
|
|||||||
A solution is to pass in a channel.
|
A solution is to pass in a channel.
|
||||||
|
|
||||||
```go
|
```go
|
||||||
type Cmd2 struct { Get bool; Val int; Ch chan<- int }
|
type Cmd2 struct {
|
||||||
|
Get bool
|
||||||
|
Val int
|
||||||
|
Ch chan<- int
|
||||||
|
}
|
||||||
|
|
||||||
func Manager2(ch <-chan Cmd2) {
|
func Manager2(ch <-chan Cmd2) {
|
||||||
val := 0
|
val := 0
|
||||||
for {
|
for {
|
||||||
c := <-ch
|
c := <-ch
|
||||||
if c.Get { c.Ch <- val }
|
if c.Get {
|
||||||
else { val = c.Val }
|
c.Ch <- val
|
||||||
|
} else {
|
||||||
|
val = c.Val
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@ -864,10 +880,18 @@ func Manager2(ch <-chan Cmd2) {
|
|||||||
To use ` Manager2 `, given a channel to it:
|
To use ` Manager2 `, given a channel to it:
|
||||||
|
|
||||||
```go
|
```go
|
||||||
func f4(ch chan<- Cmd2) int {
|
func getFromManagedChannel(ch chan<- Cmd2) int {
|
||||||
myCh := make(chan int)
|
myCh := make(chan int)
|
||||||
c := Cmd2{true, 0, myCh} // Composite literal syntax.
|
c := Cmd2{true, 0, myCh} // Composite literal syntax.
|
||||||
ch <- c
|
ch <- c
|
||||||
return <-myCh
|
return <-myCh
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
ch := make(chan Cmd2)
|
||||||
|
go Manager2(ch)
|
||||||
|
// ... come code ...
|
||||||
|
currentValue := getFromManagedChannel(ch)
|
||||||
|
// ... some more code...
|
||||||
|
}
|
||||||
```
|
```
|
Loading…
x
Reference in New Issue
Block a user