Skip to content

Instantly share code, notes, and snippets.

@caryyu
Created May 22, 2020 03:41
Show Gist options
  • Save caryyu/a205dc12f6be2a0d4729574402329c9d to your computer and use it in GitHub Desktop.
Save caryyu/a205dc12f6be2a0d4729574402329c9d to your computer and use it in GitHub Desktop.
Golang 一些示例

学习 goroutine 的异步执行并传参,具体参考:https://www.runoob.com/go/go-concurrent.html

package main

import (
	"log"
	"time"
)

func main() {
	c1 := make(chan int, 10)
	c2 := make(chan int, 10)

	go func(c1 chan int, c2 chan int) {
		for {
			select {
			case v := <-c1:
				if v == 9 {
					continue
				}
				log.Println("[goroutine] C1:", v)
			case v := <-c2:
				log.Println("[goroutine] C2:", v)
			}
		}
	}(c1, c2)

	for i := 0; i < 10; i++ {
		c1 <- i
		c2 <- i + 10
	}

	log.Println("[main] wait 10 seconds!")
	time.Sleep(time.Second * 10)
	defer close(c1)
	defer close(c2)
	log.Println("[main] application exit!")
}

输出结果

2020/05/22 11:30:07 [main] wait 10 seconds!
2020/05/22 11:30:07 [goroutine] C1: 0
2020/05/22 11:30:07 [goroutine] C2: 10
2020/05/22 11:30:07 [goroutine] C2: 11
2020/05/22 11:30:07 [goroutine] C1: 1
2020/05/22 11:30:07 [goroutine] C1: 2
2020/05/22 11:30:07 [goroutine] C1: 3
2020/05/22 11:30:07 [goroutine] C1: 4
2020/05/22 11:30:07 [goroutine] C1: 5
2020/05/22 11:30:07 [goroutine] C2: 12
2020/05/22 11:30:07 [goroutine] C1: 6
2020/05/22 11:30:07 [goroutine] C1: 7
2020/05/22 11:30:07 [goroutine] C1: 8
2020/05/22 11:30:07 [goroutine] C2: 13
2020/05/22 11:30:07 [goroutine] C2: 14
2020/05/22 11:30:07 [goroutine] C2: 15
2020/05/22 11:30:07 [goroutine] C2: 16
2020/05/22 11:30:07 [goroutine] C2: 17
2020/05/22 11:30:07 [goroutine] C2: 18
2020/05/22 11:30:07 [goroutine] C2: 19
2020/05/22 11:30:17 [main] application exit!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment