1
0
mirror of https://github.com/Mrs4s/go-cqhttp.git synced 2025-05-05 03:23:49 +08:00

rf(server): use sync.Once

This commit is contained in:
wdvxdr 2021-10-06 15:53:03 +08:00
parent b8c7941dc8
commit 19fd331c46
No known key found for this signature in database
GPG Key ID: 703F8C071DE7A1B6
2 changed files with 5 additions and 5 deletions

View File

@ -1,3 +1,4 @@
// Package servers provide servers register
package servers package servers
import ( import (

View File

@ -5,7 +5,6 @@ import (
"context" "context"
"os" "os"
"sync" "sync"
"sync/atomic"
"time" "time"
"github.com/Mrs4s/go-cqhttp/coolq" "github.com/Mrs4s/go-cqhttp/coolq"
@ -76,7 +75,7 @@ func longPolling(bot *coolq.CQBot, maxSize int) handler {
return nil return nil
} }
var ( var (
ok int32 once sync.Once
ch = make(chan []interface{}, 1) ch = make(chan []interface{}, 1)
timeout = time.Duration(p.Get("timeout").Int()) * time.Second timeout = time.Duration(p.Get("timeout").Int()) * time.Second
) )
@ -87,7 +86,7 @@ func longPolling(bot *coolq.CQBot, maxSize int) handler {
if queue.Len() == 0 { if queue.Len() == 0 {
cond.Wait() cond.Wait()
} }
if atomic.CompareAndSwapInt32(&ok, 0, 1) { once.Do(func() {
limit := int(p.Get("limit").Int()) limit := int(p.Get("limit").Int())
if limit <= 0 || queue.Len() < limit { if limit <= 0 || queue.Len() < limit {
limit = queue.Len() limit = queue.Len()
@ -97,12 +96,12 @@ func longPolling(bot *coolq.CQBot, maxSize int) handler {
ret[i] = queue.Remove(queue.Front()) ret[i] = queue.Remove(queue.Front())
} }
ch <- ret ch <- ret
} })
}() }()
if timeout != 0 { if timeout != 0 {
select { select {
case <-time.After(timeout): case <-time.After(timeout):
atomic.StoreInt32(&ok, 1) once.Do(func() {})
return coolq.OK([]interface{}{}) return coolq.OK([]interface{}{})
case ret := <-ch: case ret := <-ch:
return coolq.OK(ret) return coolq.OK(ret)