并发循环如何理解???? go for

michael_xu · · 1363 次点击
多核是通过环境变量设置的,然后才是通过go语法启用的。goroutine的调度采用的是n:m的模型,而且每一个goroutine,就是一个用户级别的线程,线程内的操作都是串行的。
#11
更多评论
你不好理解,就理解为多线程
#1
```go package main import "fmt" import "time" const ( //NUM = 10000000000000 //hang for process NUM = 1000000000 ) func f(from string) { for i := 0; i < NUM; i++ { i = i * 1 } } func main() { t0 := time.Now().UnixNano() f("direct") t := time.Now().UnixNano() go f("goroutine") t1 := time.Now().UnixNano() go func(msg string){ for i := 0; i < NUM; i++{ i = i * 1 } }("going") t2 := time.Now().UnixNano() fmt.Println("func:", t-t0, "ns, s:", (t-t0) / 1000000000) fmt.Println("go func:", t1-t, "ns, s:", (t1-t) / 1000000000) fmt.Println("go unknow func:", t2-t1, "ns, s:", (t2-t1) / 1000000000) } ``` ``` $$ time go run goroutines2.go func: 1048079427 ns, s: 1 go func: 12735 ns, s: 0 go unknow func: 1293 ns, s: 0 real 0m1.366s user 0m1.087s sys 0m0.067s ``` $ cat run.c ```c #include <string.h> #include <stdio.h> int main(){ int i; for(i=0; i < 1000000000; i++){ i = 1*i; } return 1; } ``` ``` $ time ./a.out real 0m3.970s user 0m3.030s sys 0m0.008s ```
#2