完成14.4

This commit is contained in:
glight2000
2015-12-30 17:31:42 +08:00
parent abb36a01a4
commit a6aec5bed0

View File

@@ -137,7 +137,38 @@ Received on channel 1: 94348
习惯用法:后台服务模式
服务通常是是用后台协程中的无限循环实现的,在循环中使用`select`获取并处理通道中的数据:
```go
// Backend goroutine.
func backend() {
for {
select {
case cmd := <-ch1:
// Handle ...
case cmd := <-ch2:
...
case cmd := <-chStop:
// stop server
}
}
}
```
在程序的其他地方给通道`ch1``ch2`发送数据,比如:通道`stop`用来清理结束服务程序。
另一种方式(但是不太灵活)就是(客户端)在`chRequest`上提交请求,后台协程循环这个通道,使用`switch`根据请求的行为来分别处理:
```go
func backent() {
for req := range chRequest {
switch req.Subjext() {
case A1: // Handle case ...
case A2: // Handle case ...
default:
// Handle illegal request ..
// ...
}
}
}
```
## 链接