Compare commits

...

4 Commits

Author SHA1 Message Date
独孤伶俜 d8d4475bec day10协程 串联 channel 2023-01-07 21:44:34 +08:00
独孤伶俜 31eaa11eee day10协程 没有缓存的 channel 2023-01-07 21:44:10 +08:00
独孤伶俜 c8e8947414 day10协程 2023-01-07 21:43:38 +08:00
独孤伶俜 e31d5c975f day10协程 实例 echo 2023-01-07 21:42:43 +08:00
5 changed files with 135 additions and 0 deletions

View File

@ -0,0 +1,25 @@
package main
import "runtime"
func main() {
// chan是channel的缩写channel是一种特殊的类型
// chan是一个关键字
// chan和map , slice一样是引用类型,
// 参数传递时,传递的是地址
// chan的零值是nil
// 两个相同类型的channel可以用==比较,
// 如果当他们引用的是同一个channel对象或者都是nil那么结果为true
ch := make(chan int)
ch <- 2
go forEach(ch)
runtime.GOMAXPROCS(8)
forEach(nil)
}
func forEach(ch chan int) {
for {
println(<-ch)
}
}

View File

@ -21,6 +21,7 @@ func main() {
const n = 45
fibN := fib(n) // slow
fmt.Printf("\rFibonacci(%d) = %d\n", n, fibN)
any
}
func spinner(delay time.Duration) {

View File

@ -0,0 +1,36 @@
package main
// Channels 可以用于多个goroutine之间的数据交换
func main() {
natural := make(chan int)
square := make(chan int)
// counter
go func() {
for x := 0; x <= 100; x++ {
natural <- x
}
close(natural) // 关闭channel
}()
// squarer
go func() {
for {
x, ok := <-natural
if !ok {
break // channel关闭跳出循环
}
square <- x * x
}
close(square)
}()
// printer (in main goroutine)
for {
x, ok := <-square
if !ok {
break
}
println(x)
}
}

View File

@ -0,0 +1,36 @@
package main
import (
"time"
)
// 不带缓存的channel
// 无缓存的channel发送端发送数据必须等待接收端接收数据
// 同样的, 接收数据,也必须等待发送端发送数据
// 如果有一方发了数据,但是另一方没有接收,那么就会发生阻塞
// 如果要接收数据,但是没有数据发送,那么也会发生阻塞
func main() {
ch := make(chan int)
// 模拟发送数据
go func() {
// 模拟耗时操作
time.Sleep(5 * time.Second)
ch <- 1
println("发送数据")
}()
// 程序阻塞, 等待接受数据
println("接收数据1", <-ch)
// 模拟接收数据
go func() {
// 此程序会阻塞, 因为没有数据发送
println("接收数据2", <-ch)
}()
// 模拟耗时
time.Sleep(3 * time.Second)
ch <- 2
// 模拟耗时, 等待所有的goroutine执行完毕
time.Sleep(3 * time.Second)
}

View File

@ -0,0 +1,37 @@
package main
import (
"bufio"
"fmt"
"log"
"net"
"os"
"strings"
"time"
)
func echo(c net.Conn, shout string, delay time.Duration) {
fmt.Fprintln(c, "\t", strings.ToUpper(shout))
time.Sleep(delay)
fmt.Fprintln(c, "\t", shout)
time.Sleep(delay)
fmt.Fprintln(c, "\t", strings.ToLower(shout))
}
func handleConn1(c net.Conn) {
input := bufio.NewScanner(c)
for input.Scan() {
echo(c, input.Text(), 1*time.Second)
}
// NOTE: ignoring potential errors from input.Err()
c.Close()
}
func main() {
conn, err := net.Dial("tcp", "localhost:8000")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
go mustCopy(os.Stdout, conn)
mustCopy(conn, os.Stdin)
}