Skip to content
Toggle navigation
P
Projects
G
Groups
S
Snippets
Help
黄成意
/
go_sku_server
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Issues
0
Merge Requests
0
Pipelines
Wiki
Snippets
Settings
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Commit
df518388
authored
Oct 27, 2025
by
杨树贤
Browse files
Options
_('Browse Files')
Download
Email Patches
Plain Diff
再次优化
parent
720fb45b
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
25 additions
and
6 deletions
controller/sku_controller.go
controller/sku_controller.go
View file @
df518388
...
...
@@ -146,9 +146,27 @@ func CommonController(ctx *gin.Context) map[string]interface{} {
}
// 开启一个协程,等待所有任务完成,然后关闭channel
// 使用 context 来控制这个等待协程的生命周期
go
func
()
{
wg
.
Wait
()
close
(
ch
)
// 创建一个 done channel 用于通知 wg.Wait() 完成
done
:=
make
(
chan
struct
{})
go
func
()
{
wg
.
Wait
()
close
(
done
)
}()
// 等待 wg.Wait() 完成或 context 取消
select
{
case
<-
done
:
// 所有协程都正常完成
close
(
ch
)
case
<-
ctxWithTimeout
.
Done
()
:
// context 超时,不再等待剩余协程
// 等待一小段时间让协程有机会退出
time
.
Sleep
(
300
*
time
.
Millisecond
)
close
(
ch
)
logger
.
Log
(
"等待协程完成超时,强制关闭channel"
,
"sku"
,
1
)
}
}()
//异步map最后转成map
...
...
@@ -156,7 +174,7 @@ func CommonController(ctx *gin.Context) map[string]interface{} {
for
{
select
{
case
GoodsRes
,
ok
:=
<-
ch
:
if
!
ok
{
// channel被关闭,说明所有协程都已执行完毕
if
!
ok
{
// channel被关闭,说明所有协程都已执行完毕
或超时
return
temp
}
GoodsRes
.
Range
(
func
(
k
,
v
interface
{})
bool
{
...
...
@@ -169,14 +187,15 @@ func CommonController(ctx *gin.Context) map[string]interface{} {
// context 超时或被取消
logger
.
Log
(
"协程整体处理超时,所有子协程已收到取消信号"
,
"sku"
,
1
)
//
关键:
继续从 channel 读取已经发送的数据,避免协程阻塞
//
设置一个短暂的清理超时
cleanupTimeout
:=
time
.
After
(
2
00
*
time
.
Millisecond
)
// 继续从 channel 读取已经发送的数据,避免协程阻塞
//
等待 channel 被关闭(由上面的 wg.Wait() 协程关闭)
cleanupTimeout
:=
time
.
After
(
5
00
*
time
.
Millisecond
)
for
{
select
{
case
GoodsRes
,
ok
:=
<-
ch
:
if
!
ok
{
// channel 已关闭,所有协程都已退出
logger
.
Log
(
"channel已关闭,返回结果"
,
"sku"
,
1
)
return
temp
}
// 收集已经发送的数据
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment