go例子

在thh项目中的非复用例子代码,移除项目至此

取盘子

func algorithmEatFood(cmd *cobra.Command, args []string) {

	fmt.Println("盘子")

	plate := make(chan int)
	apple := make(chan int)
	orange := make(chan int)
	go func() {
		for {
			time.Sleep(time.Second)
			dadPlate := <-plate
			fmt.Println("盘子可以放入一个水果 dad Plate", dadPlate)
			apple <- 1
			fmt.Println("dad放入一个苹果")
		}
	}()

	go func() {
		for {
			time.Sleep(time.Second)
			momPlate := <-plate
			fmt.Println("盘子可以放入一个水果mom Plate", momPlate)
			orange <- 1
			fmt.Println("mom放入一个橘子")
		}

	}()

	go func() {
		for {
			time.Sleep(time.Second)
			sonOrange := <-orange
			fmt.Println("儿子取走一个橘子 sonOrange Plate", sonOrange)
			plate <- 1
			fmt.Println("儿子清空盘子")
		}

	}()
	go func() {
		for {
			time.Sleep(time.Second)
			daughterApple := <-apple
			fmt.Println("女儿取走一个苹果 daughterApple Plate", daughterApple)
			plate <- 1
			fmt.Println("女儿清空盘子")
		}
	}()
	plate <- 1
	for {
		time.Sleep(time.Second)
	}
}

go context

func practiceContext(cmd *cobra.Command, args []string) {
	defer func() {
		fmt.Println("销毁了")
	}()
	fmt.Println("当前go数量")
	fmt.Println(runtime.NumGoroutine())

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel() // 避免其他地方忘记 cancel,且重复调用不影响
	gen := func() <-chan int {
		ch := make(chan int)
		go func() {
			var n int
			for {
				ch <- n
				n++
				time.Sleep(time.Second)
				fmt.Println(n)
			}
		}()
		return ch
	}
	for n := range gen() {
		fmt.Println("print n from for:", n)
		fmt.Println("当前go数量:", runtime.NumGoroutine())
		if n == 5 {
			break
		}
	}

	for i := 0; i < 5; i++ {
		go func(i int) {
			counter := 1
			for {
				counter += 1
				fmt.Println(i, counter)
				time.Sleep(time.Second * 1)
			}
		}(i)

		fmt.Println("当前go数量:", runtime.NumGoroutine())
	}

	time.Sleep(time.Second * 5)

	defer cancel() // 避免其他地方忘记 cancel,且重复调用不影响
	genCanQuite := func(ctx context.Context) <-chan int {
		ch := make(chan int)
		go func() {
			var n int
			for {
				select {
				case <-ctx.Done():
					return
				case ch <- n:
					n++
					time.Sleep(time.Second)
				}
			}
		}()
		return ch
	}

	for n := range genCanQuite(ctx) {
		fmt.Println(n)
		if n == 5 {
			cancel()
			break
		}
	}

}

go

func practiceGo(cmd *cobra.Command, args []string) {
	go func() {
		fmt.Println("A:我是一个来自闭包的携程,end")
	}()
	numData1 := make(chan int)
	numData2 := make(chan int)

	goB := func() {
		fmt.Println("B:我是一个来自函数的携程,end")
	}

	goC := func(numData1 chan int) {
		n := 0
		for {
			n++
			numData1 <- n
			fmt.Println("C:say2:我是一个来自函数的携程,我向通道中发出了一条数据:" + strconv.Itoa(n))
			time.Sleep(1 * time.Second)
		}
	}

	goD := func(numData2 chan int) {
		for {
			fmt.Println("我是一个会sleep的go,看看会不会阻塞,结果是没有阻塞")
			time.Sleep(time.Second * 3)
			resultNumData2 := <-numData2
			fmt.Println("D:say2:我是一个来自函数的携程,接收到通道内数据:" + strconv.Itoa(resultNumData2))
		}
	}

	goE := func() {
		for {
			fmt.Println("E:我是一个来自函数的携程,我只会这一句")
			time.Sleep(1 * time.Millisecond * 500)
		}
	}

	goF := func() {
		fmt.Println("F:我是一个来自函数的携程,我预感我将不会执行完毕end")
	}

	go goB()
	go goC(numData1)
	go goD(numData2)
	go goE()

	for i := 1; i <= 10; i++ {
		resultNumData1 := <-numData1
		numData2 <- resultNumData1
		fmt.Println("Main:我是主程,我接受到了来自C程序的信息" + cast.ToString(resultNumData1))
	}
	go goF()
}

fibonacci

func practiceFuncCase1(cmd *cobra.Command, args []string) {
	fmt.Println("多值返回")
	a, b := func() (a string, b int) {
		a = "str"
		b = 1
		return
	}()
	fmt.Println(a, b)

	startTime := arms.GetMicroTime()
	cmdFuncCounter = 1
	fmt.Println(fibonacci(46))
	endTime := arms.GetMicroTime()
	fmt.Println(float64(endTime-startTime) / 1000.0)
	fmt.Println("计数器统计方法执行次数", cmdFuncCounter)

	r := fibonacciTailCall(1000, 0, 1)
	fmt.Println(r)
	// 求第46位斐波那契数列将调用方法5942430146次
}

var (
	cmdFuncCounter int
)

func fibonacci(n int) (res int) {
	cmdFuncCounter++
	if n <= 1 {
		res = 1
	} else {
		res = fibonacci(n-1) + fibonacci(n-2)
	}
	return
}

// 尾递归
func fibonacciTailCall(n int64, result int64, preValue int64) int64 {
	if n == 0 {
		return result
	}
	return fibonacciTailCall(n-1, preValue, result+preValue)
}

defer

func practiceDefer(cmd *cobra.Command, args []string) {
	practiceDeferFunc1 := func() {
		practiceDeferFunc2 := func() {
			defer func() {
				fmt.Println("this is practiceDeferFunc2 defer")
			}()
			fmt.Println("this is practiceDeferFunc2")
		}

		defer func() {
			fmt.Println("this is practiceDeferFunc1 defer")
		}()
		fmt.Println("this is practiceDeferFunc1")
		practiceDeferFunc2()
	}

	defer func() { fmt.Println("a") }()
	defer func() { fmt.Println("b") }()
	defer func() { fmt.Println("c") }()
	practiceDeferFunc1()

	for {
		time.Sleep(time.Second)
	}
}

chan


func practiceChan(cmd *cobra.Command, args []string) {
	chanVar := make(chan int)
  // chanVar := make(chan int,10)
	go func() {
		for {
			varDad := <-chanVar
			fmt.Println("dad", varDad)
		}
	}()
	go func() {
		for {
			varMom := <-chanVar
			fmt.Println("mom", varMom)
		}
	}()

	go func() {
		for i := 0; i < 1000; i++ {
			time.Sleep(time.Second)
			chanVar <- i
		}
	}()

	for {
		time.Sleep(time.Second)
	}
}

api lock 接口限流


type httpLock struct {
	use  bool
	lock sync.Mutex
}

func (itself *httpLock) canUse(timeout int) bool {
	itself.lock.Lock()
	defer itself.lock.Unlock()
	if itself.use == true {
		return false
	} else {
		itself.use = true
		go func() {
			time.Sleep(time.Second * time.Duration(timeout))
			itself.use = false
		}()
		return true
	}
}

var apiLock httpLock

func runApiLock(cmd *cobra.Command, args []string) {

	for li := 0; li <= 10; li++ {
		if apiLock.canUse(3) {
			fmt.Println("可以访问")
		} else {
			fmt.Println("不可访问")
		}
		time.Sleep(time.Millisecond * 500)
	}
}

sort


type SortTestStruct struct {
	id int
}
func main(){
  	tmpSplice := []SortTestStruct{
		{1},
		{2},
		{3},
		{4},
		{5},
		{6},
	}
	sort.Slice(tmpSplice, func(i, j int) bool {
		return tmpSplice[i].id < tmpSplice[j].id
	})

	var Pln = fmt.Println
	Pln(tmpSplice)
}

interface

var t interface{}

func setT(vatT interface{}) {
	t = vatT
}
func getT() interface{} {
	return t
}
func main(){
	var a interface{}
	setT(1)
	a = getT()
	fmt.Println(a)
	setT("aaa")
	a = getT()
	fmt.Println(a)
}

评论列表