Skip to content

Commit

Permalink
fixed bug in awaitAll
Browse files Browse the repository at this point in the history
  • Loading branch information
alob-mtc committed Apr 27, 2023
1 parent 4725bad commit a99c483
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
14 changes: 9 additions & 5 deletions eventloop.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ var (

func Init() {
once.Do(func() {
GlobalEventLoop = &eventLoop{promiseQueue: []*Promise{}, keepAlive: true}
GlobalEventLoop = &eventLoop{promiseQueue: make([]*Promise, 0)}
})
}

Expand All @@ -31,8 +31,7 @@ type Future interface {

type eventLoop struct {
promiseQueue []*Promise
size uint64
keepAlive bool
size int64
sync sync.Mutex
}

Expand Down Expand Up @@ -94,23 +93,28 @@ func (e *eventLoop) Run() {
}

func (e *eventLoop) awaitAll() {
init := true
for {
n := len(e.promiseQueue)
if init && n == 0 {
return
}
for i := n - 1; i >= 0; i-- {
e.sync.Lock()
p := e.promiseQueue[i]
e.sync.Unlock()
if p.handler {
<-p.done
}
if currentN := int(atomic.LoadUint64(&e.size)); i == 0 && !(currentN > n) {
if currentN := int(atomic.LoadInt64(&e.size)); i == 0 && !(currentN > n) {
break
}
}
// clean up memory (promise)
e.sync.Lock()
e.promiseQueue = e.promiseQueue[n:]
atomic.StoreUint64(&e.size, e.size-uint64(n))
atomic.AddInt64(&e.size, int64(-n))
e.sync.Unlock()
init = false
}
}
2 changes: 1 addition & 1 deletion promise.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ type Promise struct {
}

func (e *eventLoop) newPromise(rev <-chan interface{}, errChan chan error) *Promise {
currentP := &Promise{id: atomic.AddUint64(&e.size, 1), rev: rev, errChan: errChan, done: make(chan struct{})}
currentP := &Promise{id: uint64(atomic.AddInt64(&e.size, 1)), rev: rev, errChan: errChan, done: make(chan struct{})}
e.sync.Lock()
e.promiseQueue = append(e.promiseQueue, currentP)
e.sync.Unlock()
Expand Down

0 comments on commit a99c483

Please sign in to comment.