连接池学习

This commit is contained in:
2025-08-15 03:53:51 +08:00
parent 0844abb869
commit c69251cc26
6 changed files with 194 additions and 0 deletions

44
goroutine/producer.go Normal file
View File

@@ -0,0 +1,44 @@
package goroutine
import (
"fmt"
"goLearn/model"
"math/rand"
"strconv"
"sync"
"time"
)
func NewProducer(ch chan model.Task, wg *sync.WaitGroup, done chan struct{}, num int, mutex *sync.Mutex, data *model.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 := model.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
}
}
}