go语句及执行规则

协程概念

MPG模型

todo

疑问

package main

import (
	"fmt"
	"runtime"
	"time"
)
func main() {
	fmt.Println("cup ",runtime.NumCPU())
	for i := 0; i < 10; i++ {
		go func() {
			fmt.Println(i, &i)
		}()
	}
	time.Sleep(time.Second)
}

输出

cup  4
4 0xc000014060
9 0xc000014060
10 0xc000014060
10 0xc000014060
10 0xc000014060
10 0xc000014060
10 0xc000014060
10 0xc000014060
10 0xc000014060
10 0xc000014060

Process finished with exit code 0

package main

import (
	"fmt"
	"runtime"
	"time"
)
func main() {
	fmt.Println("cup ",runtime.NumCPU())
	for i := 0; i < 10; i++ {
		go func(j int) {
			fmt.Println(i, j)
		}(i)
	}
	time.Sleep(time.Second)
}

输出

cup  4
7 1
8 0
8 2
10 3
10 6
10 7
10 8
10 9
10 4
10 5

Process finished with exit code 0

规则

go程序的运行会由main函数产生一个主goroutine函数,然后由go语句可以产生任意并行goroutine,由此实现了并发编程。但是,主goroutine结束,其他所有goroutine无论是什么状态都将随之结束。

衍生问题

如何控制产生goroutine的数量

todo

如何让主goroutine等待其他的goroutine都结束,它才结束

其他goroutine运行结束后通知主goroutine,主goroutine在结束即可,此思路由通道channel实现。

如何让手动启用的goroutine按照指定的顺序执行

两种方式

channel通道

自旋式

package main

import (
	"fmt"
	"sync/atomic"
	"time"
)

func main() {

	var count int32

	trigger := func(i int32, fn func()) {
		for {
			if n := atomic.LoadInt32(&count); n == i {
				fn()
				atomic.AddInt32(&count, 1)
				break
			}
			time.Sleep(time.Nanosecond)
		}
	}

	for i := int32(0); i < int32(10); i++ {
		go func(i int32) {
			fn := func() {
				fmt.Println(i)
			}
			trigger(i, fn)
		}(i)
	}

	trigger(10, func() {})

	//num := 10
	//ch := make(chan struct{}, num)
	//
	//for i := 0; i < num; i++ {
	//	go func(i int) {
	//		fmt.Println("this is goroutine :", i)
	//		ch <- struct{}{}
	//	}(i)
	//}
	//
	//for j := 0; j < num; j++ {
	//	<- ch
	//}
}

 

你可能感兴趣的:(go语言核心36讲,go用户级线程,go协程)