Commit 82dff93b by hcy

并发问题

parent 3a6792ae
......@@ -117,8 +117,8 @@ func CommonController(ctx *gin.Context) map[string]interface{} {
var wg sync.WaitGroup
ch := make(chan sync.Map, 50) //管道
wgMax := 3 //线程数量最多多少
wgcount := 0 //当前线程数
//wgMax := 3 //线程数量最多多少
//wgcount := 0 //当前线程数
temp := make(map[string]interface{}) //最后输出计算结果
for _, goodsId := range goodsIdArr {
......@@ -164,32 +164,34 @@ func CommonController(ctx *gin.Context) map[string]interface{} {
// 启动协程,传递独立的 context 和参数,而不是 gin.Context
go func(ctx context.Context, params service.RequestParams, skuStr, goodsId, spuStr string, ch chan sync.Map) {
defer wg.Done()
//defer wg.Done()
defer func() { <-ch }()
lyService.LyGoodsDetail(ctx, params, skuStr, goodsId, spuStr, ch)
}(ctx, requestParams, skuStr, goodsId, redisLySpuArr[spuId], ch)
wg.Add(1)
wgcount += 1
//wg.Add(1)
// wgcount += 1
if wgcount >= wgMax {
println("线程数量:" + gconv.String(wgcount))
wg.Wait() // 等待所有登记的goroutine都结束
wgcount = 0
}
//if wgcount >= wgMax {
// println("线程数量:" + gconv.String(wgcount))
// wg.Wait() // 等待所有登记的goroutine都结束
// wgcount = 0
//}
}
}
if wgcount > 0 {
//println("等待结束,现有运行线程数:" + gconv.String(wgcount))
//wg.Wait()
}
close(ch)
//if wgcount > 0 {
// //println("等待结束,现有运行线程数:" + gconv.String(wgcount))
// //wg.Wait()
//}
//wg.Wait()
//异步map最后转成map
for {
select {
case GoodsRes, ok := <-ch:
if !ok { // channel被关闭,说明所有协程都已执行完毕或超时
close(ch)
return temp
}
GoodsRes.Range(func(k, v interface{}) bool {
......@@ -199,10 +201,10 @@ func CommonController(ctx *gin.Context) map[string]interface{} {
})
case <-time.After(20 * time.Second):
println("协程超时20秒")
close(ch)
return temp
}
}
}
func Synchronization(ctx *gin.Context) {
......
......@@ -10,6 +10,7 @@ import (
"go_sku_server/service/sorter"
"sort"
"sync"
"time"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
......@@ -38,6 +39,7 @@ type Power struct {
*/
func (ls *LyService) LyGoodsDetail(ctx context.Context, params RequestParams, skuStr, goodsId, spuStr string, ch chan sync.Map) {
start_time := gconv.String(time.Now().UnixMilli())
redisConn := gredis.Conn("search_r")
redisConnSpu := gredis.Conn("spu")
// 连接prev_sku MongoDB
......@@ -273,6 +275,7 @@ func (ls *LyService) LyGoodsDetail(ctx context.Context, params RequestParams, sk
//退出通道
ch <- GoodsRes
println("-----goodsId:" + goodsId + "--start_time:" + start_time + " ---end_time:" + gconv.String(time.Now().UnixMilli()))
}
// 获取活动
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment