添加协程结构

This commit is contained in:
2025-08-13 07:11:17 +08:00
parent eb5a502d67
commit fda6593f80
4 changed files with 83 additions and 2 deletions

27
goroutine/consumer.go Normal file
View File

@@ -0,0 +1,27 @@
package goroutine
import (
"fmt"
"sync"
"toutoukan/model/routine"
)
func NewConsumer(ch chan routine.Task, wg *sync.WaitGroup, done chan struct{}, num int, data *routine.Data, rwmutex *sync.RWMutex) {
defer wg.Done()
for {
select {
case <-ch:
rwmutex.RLock()
fmt.Printf("消费者%d号处理消息统计消息总数为%d\n", num+1, data.Count)
fmt.Printf("消费者%d号当前记录详情如下\n", num+1)
for key, value := range data.Record {
fmt.Printf(" 键:%d%d\n", key, value)
}
rwmutex.RUnlock()
case <-done:
fmt.Printf("消费者%d号退出接收\n", num+1)
return
}
}
}

44
goroutine/producer.go Normal file
View File

@@ -0,0 +1,44 @@
package goroutine
import (
"fmt"
"math/rand"
"strconv"
"sync"
"time"
"toutoukan/model/routine"
)
func NewProducer(ch chan routine.Task, wg *sync.WaitGroup, done chan struct{}, num int, mutex *sync.Mutex, data *routine.Data, rwmutex *sync.RWMutex) {
defer wg.Done()
timech := time.Tick(1 * time.Second)
rand.Seed(time.Now().UnixNano())
for {
select {
case <-timech:
fmt.Printf("生产者%d号上锁\n", num+1)
randnum := rand.Intn(100)
task := routine.Task{
Id: strconv.Itoa(randnum),
Content: "访问数据库",
}
mutex.Lock()
data.Count += 1
mutex.Unlock()
rwmutex.Lock()
data.Record[randnum] += 1
rwmutex.Unlock()
fmt.Printf("生产者%d号注入编号为%s,内容为:%s\n", num+1, task.Id, task.Content)
ch <- task
fmt.Printf("生产者%d号释放锁\n", num+1)
case <-done:
fmt.Printf("生产者%d号退出任务\n", num+1)
return
}
}
}