Skip to content

Instantly share code, notes, and snippets.

@tangx
Created November 19, 2019 01:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tangx/bacf4840160f4c9e7eb208dfec2f67dc to your computer and use it in GitHub Desktop.
Save tangx/bacf4840160f4c9e7eb208dfec2f67dc to your computer and use it in GitHub Desktop.
golang 通道
package gochannel
import (
"fmt"
"math/rand"
"sync"
"time"
)
// 创建 wg
var wg sync.WaitGroup
func gochan() {
ch := make(chan int, 4)
// 增加 1 个锁
wg.Add(1)
go Sender(ch)
go Reciver(ch)
// 等待锁释放
wg.Wait()
}
func Sender(ch chan int) {
for i := 0; i < 10; i++ {
rand.Seed(time.Now().UnixNano())
n := rand.Intn(1)
time.Sleep(time.Duration(n) * time.Second)
ch <- i
fmt.Printf("-> Send %d, Cooldown %d s\n", i, n)
}
// 关闭 ch
// https://colobu.com/2016/04/14/Golang-Channels/#close
close(ch)
}
func Reciver(ch chan int) {
// 释放
defer wg.Done()
for i := range ch {
rand.Seed(time.Now().UnixNano())
n := rand.Intn(4)
fmt.Printf("<- Recived %d , CoolDonw %d s\n", i, n)
time.Sleep(time.Duration(n) * time.Second)
}
}
@tangx
Copy link
Author

tangx commented Nov 19, 2019

// -> Send 0, Cooldown 0 s
// -> Send 1, Cooldown 0 s
// -> Send 2, Cooldown 0 s
// <- Recived 0 , CoolDonw 0 s
// -> Send 3, Cooldown 0 s
// -> Send 4, Cooldown 0 s
// -> Send 5, Cooldown 0 s
// <- Recived 1 , CoolDonw 3 s
// <- Recived 2 , CoolDonw 2 s
// -> Send 6, Cooldown 0 s
// -> Send 7, Cooldown 0 s
// <- Recived 3 , CoolDonw 2 s
// <- Recived 4 , CoolDonw 2 s
// -> Send 8, Cooldown 0 s
// <- Recived 5 , CoolDonw 2 s
// -> Send 9, Cooldown 0 s
// <- Recived 6 , CoolDonw 3 s
// <- Recived 7 , CoolDonw 3 s
// <- Recived 8 , CoolDonw 1 s
// <- Recived 9 , CoolDonw 2 s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment