5-1 goroutine.mp4

  1. package main
  2. import "fmt"
  3. func main() {
  4. //fmt.Printf("hellow from goroutine %d")
  5. for i := 0; i < 10; i++ {
  6. go func(ii int) {
  7. for {
  8. fmt.Printf("hellow from goroutine %d\n", ii)
  9. }
  10. }(i)
  11. }
  12. select {}
  13. }

携程
Coroutine

  • 轻量级”线程”
  • 非抢占式 多任务处理,由携程主动交出控制权 ``` package main

import ( “fmt” “time” )

func main() { //fmt.Printf(“hellow from goroutine %d”) var a [10]int for i := 0; i < 10; i++ { go func(i int) { for { a[i]++ //fmt.Printf(“hellow from goroutine %d\n”, ii) } }(i) } time.Sleep(time.Millisecond) fmt.Println(a) } /** [452860 456018 32360 77853 13509 368659 62929 151728 74805 319663]

Process finished with the exit code 0 */

  1. ```
  2. package main
  3. import (
  4. "fmt"
  5. "runtime"
  6. "time"
  7. )
  8. func main() {
  9. //fmt.Printf("hellow from goroutine %d")
  10. var a [10]int
  11. for i := 0; i < 10; i++ {
  12. go func(i int) {
  13. for {
  14. a[i]++
  15. //fmt.Printf("hellow from goroutine %d\n", ii)
  16. // 交出控制权
  17. runtime.Gosched()
  18. }
  19. }(i)
  20. }
  21. time.Sleep(time.Millisecond)
  22. fmt.Println(a)
  23. }
  24. /**
  25. [655 669 635 667 532 582 608 503 578 539]
  26. Process finished with the exit code 0
  27. */

不明觉厉,他们有什么区别???

如果不传递i
会发生:

  1. package main
  2. import (
  3. "fmt"
  4. "runtime"
  5. "time"
  6. )
  7. func main() {
  8. //fmt.Printf("hellow from goroutine %d")
  9. var a [10]int
  10. for i := 0; i < 10; i++ {
  11. go func() {
  12. // race condition
  13. for {
  14. a[i]++
  15. //fmt.Printf("hellow from goroutine %d\n", ii)
  16. // 交出控制权
  17. runtime.Gosched()
  18. }
  19. }()
  20. }
  21. time.Sleep(time.Millisecond)
  22. fmt.Println(a)
  23. }
  24. /**
  25. PS E:\Projects\GolandProjects\go-camp\mooc\code\learngo\goroutine> go run .\goroutine.go -race
  26. panic: runtime error: index out of range [10] with length 10
  27. goroutine 15 [running]:
  28. main.main.func1()
  29. E:/Projects/GolandProjects/go-camp/mooc/code/learngo/goroutine/goroutine.go:16 +0x56
  30. created by main.main
  31. E:/Projects/GolandProjects/go-camp/mooc/code/learngo/goroutine/goroutine.go:13 +0x57
  32. panic: runtime error: index out of range [10] with length 10
  33. goroutine 10 [running]:
  34. main.main.func1()
  35. E:/Projects/GolandProjects/go-camp/mooc/code/learngo/goroutine/goroutine.go:16 +0x56
  36. created by main.main
  37. E:/Projects/GolandProjects/go-camp/mooc/code/learngo/goroutine/goroutine.go:13 +0x57
  38. exit status 2
  39. PS E:\Projects\GolandProjects\go-camp\mooc\code\learngo\goroutine>
  40. */

5-2 go语言的调度器.mp4

携程特点

  • 轻量级的线程
  • 非抢占式多任务处理,有携程主动交出控制权
  • 编译器/解释器/虚拟机层面的多任务
  • 多个携程可能在一个或者多个线程上运行

1635298652252
1635298661528
1635299352365
1635299432245
1635299442761
1635299631845

  • 任何函数只需加上go就能送给调度器运行
  • 不需要在定义时区分是否是异步函数
  • 调度器在合适的点进行切换
  • 使用-race来检测数据访问冲突

1635300094530