我能用多少个 ?goroutine?比如维基百科说 Erlang 可在不降低性能的情况下,在不降低性能的情况下。1 r) U* k8 z% |5 v 更新:我刚刚调查了 goroutines 性能并得到这样的结果:" b6 M4 i6 [* \8 y# p0 `3 j 看起来 goroutine 生命周期比 sqrt() 计算 1000 次(对我来说大约是 45μs)更重要的是,唯一的限制是内存6 {& y& J3 P0 N9 `5 A) z6 m/ E
Goroutine花费 4 - 4.5 KB . J/ Z! u$ p' y& Y4 n% b/ J 解决方案: , n( ~5 C% _' u9 V" _8 |! K 如果一个 goroutine 被堵塞,除:- D" a0 a) a! B4 l; H 使用内存3 b7 I( q& O3 W: a
垃圾收集较慢成本goroutine 平均时间为: 7 O, P( V8 W K5 a1 }. n7 N
Go 1.6.2 (April 2016) 32-bit x86 CPU (A10-7850K 4GHz) | Number of goroutines: 100000 | Per goroutine: | Memory: 4536.84 bytes | Time: 1.634248 μs 64-bit x86 CPU (A10-7850K 4GHz) | Number of goroutines: 100000 | Per goroutine: | Memory: 4707.92 bytes | Time: 1.842097 μsGo release.r60.3 (December 2011) 32-bit x86 CPU (1.6 GHz) | Number of goroutines: 100000 | Per goroutine: | Memory: 4243.45 bytes | Time: 5.815950 μs 5 a4 o6 u$ j! s' g8 i& |1 d. {( K
package mainimport "flag" "fmt" "os" "runtime" "time")var n = flag.Int("n",1e5,"Number of goroutines to create")var ch = make(chan byte)var counter = 0func f() counter <-ch // Block this goroutine}func main() flag.Parse() if *n <= fmt.Fprintf(os.Stderr,"invalid number of goroutines") os.Exit(1) Limit the number of spare OS threads to just 1 runtime.GOMAXPROCS(1) / Make a copy of MemStats var m0 runtime.MemStats runtime.ReadMemStats(&m0) t0 := time.Now().UnixNano() for i := 0; i < *n; i go f() } runtime.Gosched() t1 := time.Now().UnixNano() runtime.GC() // Make a copy of MemStats var m1 runtime.MemStats runtime.ReadMemStats(&m1) if counter != *n fmt.Fprintf(os.Stderr,"failed to begin execution of all goroutines") os.Exit(1) fmt.Printf("Number of goroutines: %d\n",*n) fmt.Printf("er goroutine:\n") fmt.Printf(" Memory: %.2f bytes\n",float64(m1.Sys-m0.Sys)/float64(*n)) fmt.Printf(" Time: %f μs\n",float64(t1-t0)/float64(*n)/1e3)}6 H& C7 l( W3 ?1 A. |4 x& Q6 S