```go
package main
import "fmt"
func f(from string) {
for i := 0; i < 3; i++ {
fmt.Println(from, ":", i)
}
}
func main() {
go f("test")
var input string
fmt.Scanln(&input)
fmt.Println("done")
}
```
很简单的代码,但是这样做的实质作用是什么? 难道go for 循环是把i 进行切分然后多核进行运算的?
多核是通过环境变量设置的,然后才是通过go语法启用的。goroutine的调度采用的是n:m的模型,而且每一个goroutine,就是一个用户级别的线程,线程内的操作都是串行的。
#11
更多评论
```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