ch8/ch8-04 #168
Replies: 7 comments 12 replies
-
无缓冲通道必须在单独goroutine工作,在main中会死锁,个人总结:
|
Beta Was this translation helpful? Give feedback.
-
这里必须使用range,for取完了,即使关闭了通道,在goroutine内还是会取到0值
} 最后输出 |
Beta Was this translation helpful? Give feedback.
-
类型chan<- int表示一个只发送int的channel,只能发送不能接收。 |
Beta Was this translation helpful? Give feedback.
-
一段使用go协程和 package main
import (
"fmt"
"math"
"time"
)
const (
UPPER = 1e2
)
func source(out chan<- int) {
for i := 2; i <= UPPER; i++ {
out <- i
}
close(out)
}
func cull(p int, in <-chan int, out chan<- int) {
for n := range in {
if n%p != 0 {
out <- n
}
}
close(out)
}
func sink(in <-chan int) {
for {
p, ok := <-in
if !ok {
break
}
fmt.Print(p, " ")
ch := make(chan int)
go cull(p, in, ch)
in = ch
}
}
func timer(name string) func() {
start := time.Now()
return func() {
fmt.Printf("%s took %v to execute\n", name, time.Since(start))
}
}
// sieve of Eratosthene
// ref: https://www.cs.dartmouth.edu/~doug/sieve/sieve.pdf
func csp() {
defer timer("csp")()
ch := make(chan int)
go source(ch)
sink(ch)
fmt.Println()
}
func plainPrime() {
defer timer("plainPrime")()
for i := 2; i <= UPPER; i++ {
isPrime := true
for j := 2; j <= int(math.Sqrt(float64(i))); j++ {
if i%j == 0 {
isPrime = false
break
}
}
if isPrime {
fmt.Printf("%d ", i)
}
}
fmt.Println()
}
func main() {
csp()
plainPrime()
} |
Beta Was this translation helpful? Give feedback.
-
8.3package main
import (
"io"
"log"
"net"
"os"
)
func main() {
conn, err := net.Dial("tcp", ":8088")
if err != nil {
log.Fatal(err)
}
// 空结构体尺寸为0,通常当作信号来传播
ch := make(chan struct{})
go func() {
io.Copy(os.Stdout, conn)
log.Println("done")
// 发送信号,让等待阻塞的main函数继续执行
ch <- struct{}{}
}()
mustCopy(conn, os.Stdin)
// 标准输入流关闭后,关闭conn的输入流
conn.(*net.TCPConn).CloseWrite()
// 阻塞等待服务端消息结束
<-ch
}
func mustCopy(dst io.Writer, src io.Reader) {
_, err := io.Copy(dst, src)
// 注释这里,不然读取到eof会直接退出程序
// log.Fetal(err)
} |
Beta Was this translation helpful? Give feedback.
-
当一个被关闭的channel中已经发送的数据都被成功接收后,后续的接收操作将不再阻塞,它们会立即返回一个零值。这个设计容易埋坑啊。 |
Beta Was this translation helpful? Give feedback.
-
操作不同状态的chan会引发三种行为:
|
Beta Was this translation helpful? Give feedback.
-
ch8/ch8-04
中文版
https://gopl-zh.github.io/ch8/ch8-04.html
Beta Was this translation helpful? Give feedback.
All reactions