重写多协程问题

This commit is contained in:
JACKYMYPERSON
2025-08-31 13:10:56 +08:00
parent ee1bbb59a4
commit 42d65b3562
3 changed files with 60 additions and 2 deletions

19
test/Consumer.go Normal file
View File

@@ -0,0 +1,19 @@
package test
import (
"fmt"
"sync"
)
func GoConsumer(mx *sync.Mutex, ch chan int) {
defer mx.Unlock()
for {
select {
case v := <-ch:
mx.Lock()
fmt.Println("读取到", v)
mx.Unlock()
}
}
}

25
test/Producer.go Normal file
View File

@@ -0,0 +1,25 @@
package test
import (
"math/rand"
"sync"
"time"
)
func GoProducer(mx *sync.Mutex, ch chan int) {
rand.Seed(time.Now().UnixNano())
// 生成 [0,100) 随机整数
randomInt := rand.Intn(100)
timech := time.Tick(time.Second)
defer mx.Unlock()
for {
select {
case <-timech:
ch <- randomInt
}
}
}