Created
November 19, 2019 01:06
-
-
Save tangx/bacf4840160f4c9e7eb208dfec2f67dc to your computer and use it in GitHub Desktop.
golang 通道
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
Author
tangx
commented
Nov 19, 2019
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment