async: work both go and llgo

This commit is contained in:
Li Jie
2024-09-04 17:08:08 +08:00
parent d4a72bf661
commit 1a158b5de3
11 changed files with 441 additions and 151 deletions

View File

@@ -17,11 +17,7 @@
package async
import (
"context"
"unsafe"
_ "unsafe"
"github.com/goplus/llgo/c/libuv"
)
type Void = [0]byte
@@ -30,16 +26,13 @@ type Future[T any] func() T
type IO[T any] func(e *AsyncContext) Future[T]
type Chain[T any] func(callback func(T))
func (f Future[T]) Do(callback func(T)) {
callback(f())
type AsyncContext struct {
*Executor
complete func()
}
type AsyncContext struct {
context.Context
*Executor
Complete func()
func (ctx *AsyncContext) Complete() {
ctx.complete()
}
func Async[T any](fn func(resolve func(T))) IO[T] {
@@ -53,93 +46,9 @@ func Async[T any](fn func(resolve func(T))) IO[T] {
})
return func() T {
if !done {
panic("AsyncIO: Future accessed before completion")
panic("async.Async: Future accessed before completion")
}
return result
}
}
}
type bindAsync struct {
libuv.Async
cb func()
}
func BindIO[T any](call IO[T], callback func(T)) {
loop := Exec().L
a := &bindAsync{}
loop.Async(&a.Async, func(p *libuv.Async) {
(*bindAsync)(unsafe.Pointer(p)).cb()
})
ctx := &AsyncContext{
Context: context.Background(),
Executor: Exec(),
Complete: func() {
a.Async.Send()
},
}
f := call(ctx)
a.cb = func() {
a.Async.Close(nil)
result := f()
callback(result)
}
}
// -----------------------------------------------------------------------------
func Await[T1 any](call IO[T1]) (ret T1) {
ch := make(chan struct{})
f := call(&AsyncContext{
Context: context.Background(),
Executor: Exec(),
Complete: func() {
close(ch)
},
})
<-ch
return f()
}
func Race[T1 any](calls ...IO[T1]) IO[T1] {
return Async(func(resolve func(T1)) {
done := false
for _, call := range calls {
var f Future[T1]
f = call(&AsyncContext{
Context: context.Background(),
Executor: Exec(),
Complete: func() {
if done {
return
}
done = true
resolve(f())
},
})
}
})
}
func All[T1 any](calls ...IO[T1]) IO[[]T1] {
return Async(func(resolve func([]T1)) {
n := len(calls)
results := make([]T1, n)
done := 0
for i, call := range calls {
i := i
var f Future[T1]
f = call(&AsyncContext{
Context: context.Background(),
Executor: Exec(),
Complete: func() {
results[i] = f()
done++
if done == n {
resolve(results)
}
},
})
}
})
}