ch8: fix code format

This commit is contained in:
chai2010
2016-01-21 10:39:06 +08:00
parent 0b5ec941ed
commit b1730821fe
13 changed files with 393 additions and 404 deletions

View File

@@ -10,17 +10,17 @@ Go語言併沒有提供在一個goroutine中終止另一個goroutine的方法
隻要一些小脩改我們就可以把退出邏輯加入到前一節的du程序。首先我們創建一個退出的channel這個channel不會向其中發送任何值但其所在的閉包內要寫明程序需要退出。我們同時還定義了一個工具函數cancelled這個函數在被調用的時候會輪詢退出狀態。
<u><i>gopl.io/ch8/du4</i></u>
```go
gopl.io/ch8/du4
var done = make(chan struct{})
func cancelled() bool {
select {
case <-done:
return true
default:
return false
}
select {
case <-done:
return true
default:
return false
}
}
```
@@ -29,8 +29,8 @@ func cancelled() bool {
```go
// Cancel traversal when input is detected.
go func() {
os.Stdin.Read(make([]byte, 1)) // read a single byte
close(done)
os.Stdin.Read(make([]byte, 1)) // read a single byte
close(done)
}()
```
@@ -38,16 +38,16 @@ go func() {
```go
for {
select {
case <-done:
// Drain fileSizes to allow existing goroutines to finish.
for range fileSizes {
// Do nothing.
}
return
case size, ok := <-fileSizes:
// ...
}
select {
case <-done:
// Drain fileSizes to allow existing goroutines to finish.
for range fileSizes {
// Do nothing.
}
return
case size, ok := <-fileSizes:
// ...
}
}
```
@@ -55,13 +55,13 @@ walkDir這個goroutine一啟動就會輪詢取消狀態如果取消狀態被
```go
func walkDir(dir string, n *sync.WaitGroup, fileSizes chan<- int64) {
defer n.Done()
if cancelled() {
return
}
for _, entry := range dirents(dir) {
// ...
}
defer n.Done()
if cancelled() {
return
}
for _, entry := range dirents(dir) {
// ...
}
}
```
@@ -71,13 +71,13 @@ func walkDir(dir string, n *sync.WaitGroup, fileSizes chan<- int64) {
```go
func dirents(dir string) []os.FileInfo {
select {
case sema <- struct{}{}: // acquire token
case <-done:
return nil // cancelled
}
defer func() { <-sema }() // release token
// ...read directory...
select {
case sema <- struct{}{}: // acquire token
case <-done:
return nil // cancelled
}
defer func() { <-sema }() // release token
// ...read directory...
}
```