添加协程结构
This commit is contained in:
@@ -7,7 +7,6 @@ import (
|
||||
"toutoukan/model/article"
|
||||
)
|
||||
|
||||
// 全局索引变量,避免重复创建
|
||||
var GlobalIndex bleve.Index
|
||||
|
||||
func DataSearch(c *gin.Context) {
|
||||
@@ -78,7 +77,7 @@ func DataSearch(c *gin.Context) {
|
||||
}
|
||||
|
||||
c.JSON(200, gin.H{
|
||||
"total": len(results), // 返回实际有效结果数
|
||||
"total": len(results),
|
||||
"took": searchResult.Took,
|
||||
"result": results,
|
||||
})
|
||||
|
||||
27
goroutine/consumer.go
Normal file
27
goroutine/consumer.go
Normal 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
44
goroutine/producer.go
Normal 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
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
11
model/routine/model.go
Normal file
11
model/routine/model.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package routine
|
||||
|
||||
type Task struct {
|
||||
Id string
|
||||
Content string
|
||||
}
|
||||
|
||||
type Data struct {
|
||||
Count int
|
||||
Record map[int]int
|
||||
}
|
||||
Reference in New Issue
Block a user