diff --git a/eventloop.go b/eventloop.go index 64c94cc..7e63b6d 100644 --- a/eventloop.go +++ b/eventloop.go @@ -13,41 +13,38 @@ var ( GlobalEventLoop *eventLoop ) -func Init() { - queue := []func() bool{} - var lock sync.Mutex +func InitGlobalEventLoop() Future { once.Do(func() { - GlobalEventLoop = &eventLoop{promiseQueue: make([]*Promise, 0)} - }) - // TODO: add evnt loop - go func() { - for work := range eventBus { - lock.Lock() - queue = append(queue, *work) - lock.Unlock() - } - }() + queue := []func() bool{} + var lock sync.Mutex + // event loop + go func() { + for work := range eventBus { + lock.Lock() + queue = append(queue, *work) + lock.Unlock() + } + }() - go func() { - for { - n := len(queue) - retry := []func() bool{} - for i := 0; i < n; i++ { - currentWork := queue[i] + go func() { + for { + n := len(queue) + retry := []func() bool{} + for i := 0; i < n; i++ { + currentWork := queue[i] - if done := currentWork(); !done { - retry = append(retry, currentWork) + if done := currentWork(); !done { + retry = append(retry, currentWork) + } } + lock.Lock() + queue = queue[n:] + queue = append(queue, retry...) + lock.Unlock() } - lock.Lock() - queue = queue[n:] - queue = append(queue, retry...) - lock.Unlock() - } - }() -} - -func GetGlobalEventLoop() Future { + }() + GlobalEventLoop = &eventLoop{promiseQueue: make([]*Promise, 0)} + }) return GlobalEventLoop }