Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
newhuangchuan authored May 13, 2022
1 parent 022161d commit 6ebefd4
Show file tree
Hide file tree
Showing 2 changed files with 105 additions and 0 deletions.
46 changes: 46 additions & 0 deletions week3-channeel/channel_select_optimization.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package main

import (
"fmt"
"math/rand"
"sync"
"time"
)

func main() {
var wg sync.WaitGroup
wg.Add(1)
//需要初始化随机数的资源库,如果不执行这一行,不管运行多少次都是返回相同的值
rand.Seed(time.Now().UnixNano())
no := rand.Intn(6)
fmt.Printf("[no is %d, type is %T]\n", no, no)
no *= 1000
du := time.Duration(int32(no)) * time.Millisecond
fmt.Println("timeout duration is :", du)
wg.Done()
if isTimeout(&wg, du) {
fmt.Println("Time out")
} else {
fmt.Println("Not time out ")
}

}


func isTimeout(wg *sync.WaitGroup, du time.Duration) bool {
ch1 := make(chan int)
go func() {
time.Sleep(3 * time.Second)
defer close(ch1)
wg.Wait()
}()

select {
case <- ch1:
return false
case <- time.After(du):
return true

}
}
//这是一种模拟,让程序的等待时间可以更具传入参数进行不同的超时间长判断, 这里是用随机数来模拟时长的,真实的项目中可以根据配置参数或者统计参数在运行时传递到函数中。
59 changes: 59 additions & 0 deletions week3-channeel/pipeline.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package main

import (
"fmt"
"math/rand"
)

//channel 可以连接goroutine,如果一个goroutine的输出是拎一个goroutine的输入,就叫做pipeline。可以理解为pipeline是虚拟的,用来连接goroutine和channel,并且最终形成一个goroutine的输出成为另一个goroutine的输入,且是使用channel传递数据的。
//使用pipeline的好处有三点:
//首先,在程序中形成一个清晰稳定的数据流,我们在使用的时候不需要过多考虑gorouine和channel的相关通信和状态问题。
//其次,在一个pipeline内,不需要把数据再保存为变量,节省了内存空间并提高了效率。
//最后,使用pipeline能够简化程序的复杂度,便于维护
var done = false
var Mess = make(map[int]bool)

func main() {
A := make(chan int)
B := make(chan int)
go sendRan(50, 10, A)
go receive(B, A)
sum(B)
}

func genRandom(max, min int) int {
return rand.Intn(max - min) + min
}

func sendRan(max, min int, out chan int) {
for {
if done {
close(out)
return
}
out <- genRandom(max, min)
}
}

func receive(out chan<- int, in <-chan int) {
for r := range in {
fmt.Println(" " , r)
_, ok := Mess[r]
if ok {
fmt.Println("duplicate num is : ", r)
done = true
} else {
Mess[r] = true
out <- r
}
}
close(out)
}

func sum(in <-chan int) {
var sum int
for i := range in {
sum += i
}
fmt.Println("The sum is : ", sum)
}

0 comments on commit 6ebefd4

Please sign in to comment.