golang 片段7 for https://medium.com/@francesc/why-are-there-nil-channels-in-go-9877cc0b2308
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang 片段7 for https://medium.com/@francesc/why-are-there-nil-channels-in-go-9877cc0b2308相关的知识,希望对你有一定的参考价值。
func merge(a, b <-chan int) <-chan int {
c := make(chan int)
go func() {
defer close(c)
for a != nil || b != nil {
select {
case v, ok := <-a:
if !ok {
fmt.Println("a is done")
a = nil
continue
}
c <- v
case v, ok := <-b:
if !ok {
fmt.Println("b is done")
b = nil
continue
}
c <- v
}
}
}()
return c
}
golang 转到片段以观察运行时行为和内存分配
// This snippet is helpful for observing OS threads as the runtime is creating
// blocked out of the gate goroutines. These should immediately be going off of
// CPU and remaining this way for the entirety of the process's lifetime.
package main
import (
"fmt"
"os"
"runtime"
"time"
"net/http"
_ "net/http/pprof"
)
func main() {
const limit = 100000
go func() {
fmt.Println(http.ListenAndServe(":9876", nil))
}()
for i := 0; i < limit; i++ {
c := make(chan struct{})
go func() {
<-c
}()
}
fmt.Fprintf(os.Stdout, "Number of goroutines: %d\n", runtime.NumGoroutine())
<-time.NewTimer(600 * time.Second).C
}
// This snippet is helpful for observing OS threads as the runtime is creating
// blocked out of the gate goroutines. These should immediately be going off of
// CPU and remaining this way for the entirety of the process's lifetime.
package main
import (
"fmt"
"os"
"runtime"
"time"
)
func main() {
for {
fmt.Fprintf(os.Stderr, "%d ", runtime.NumGoroutine())
c := make(chan struct{})
go func() {
<-c
}()
<-time.NewTimer(time.Second).C
}
}
以上是关于golang 片段7 for https://medium.com/@francesc/why-are-there-nil-channels-in-go-9877cc0b2308的主要内容,如果未能解决你的问题,请参考以下文章