连接池学习
This commit is contained in:
26
goroutine/consumer.go
Normal file
26
goroutine/consumer.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package goroutine
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"goLearn/model"
|
||||
"sync"
|
||||
)
|
||||
|
||||
func NewConsumer(ch chan model.Task, wg *sync.WaitGroup, done chan struct{}, num int, data *model.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
44
goroutine/producer.go
Normal 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
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user