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

@@ -5,7 +5,6 @@ import (
"os"
"time"
"github.com/goplus/llgo/c"
"github.com/goplus/llgo/x/async"
"github.com/goplus/llgo/x/async/timeout"
"github.com/goplus/llgo/x/tuple"
@@ -31,10 +30,9 @@ func WriteFile(fileName string, content []byte) async.IO[error] {
func sleep(i int, d time.Duration) async.IO[int] {
return async.Async(func(resolve func(int)) {
go func() {
c.Usleep(c.Uint(d.Microseconds()))
async.BindIO(timeout.Timeout(d), func(async.Void) {
resolve(i)
}()
})
})
}
@@ -46,6 +44,8 @@ func main() {
}
func RunIO() {
println("RunIO with Await")
async.Run(func() {
content, err := async.Await(ReadFile("1.txt")).Get()
if err != nil {
@@ -62,6 +62,7 @@ func RunIO() {
})
// Translated to in Go+:
println("RunIO with BindIO")
async.Run(func() {
async.BindIO(ReadFile("1.txt"), func(v tuple.Tuple2[[]byte, error]) {
@@ -84,30 +85,42 @@ func RunIO() {
}
func RunAllAndRace() {
ms100 := 100 * time.Millisecond
ms200 := 200 * time.Millisecond
ms300 := 300 * time.Millisecond
println("Run All with Await")
async.Run(func() {
all := async.All(sleep(1, time.Second), sleep(2, time.Second*2), sleep(3, time.Second*3))
all := async.All(sleep(1, ms200), sleep(2, ms100), sleep(3, ms300))
async.BindIO(all, func(v []int) {
fmt.Printf("All: %v\n", v)
})
})
println("Run Race with Await")
async.Run(func() {
first := async.Race(sleep(1, time.Second), sleep(2, time.Second*2), sleep(3, time.Second*3))
first := async.Race(sleep(1, ms200), sleep(2, ms100), sleep(3, ms300))
v := async.Await(first)
fmt.Printf("Race: %v\n", v)
})
// Translated to in Go+:
println("Run All with BindIO")
async.Run(func() {
all := async.All(sleep(1, time.Second), sleep(2, time.Second*2), sleep(3, time.Second*3))
all := async.All(sleep(1, ms200), sleep(2, ms100), sleep(3, ms300))
async.BindIO(all, func(v []int) {
fmt.Printf("All: %v\n", v)
})
})
println("Run Race with BindIO")
async.Run(func() {
first := async.Race(sleep(1, time.Second), sleep(2, time.Second*2), sleep(3, time.Second*3))
first := async.Race(sleep(1, ms200), sleep(2, ms100), sleep(3, ms300))
async.BindIO(first, func(v int) {
fmt.Printf("Race: %v\n", v)
})
@@ -115,17 +128,21 @@ func RunAllAndRace() {
}
func RunTimeout() {
println("Run Timeout with Await")
async.Run(func() {
fmt.Printf("Start 1 second timeout\n")
async.Await(timeout.Timeout(1 * time.Second))
fmt.Printf("Start 100 ms timeout\n")
async.Await(timeout.Timeout(100 * time.Millisecond))
fmt.Printf("timeout\n")
})
// Translated to in Go+:
println("Run Timeout with BindIO")
async.Run(func() {
fmt.Printf("Start 1 second timeout\n")
async.BindIO(timeout.Timeout(1*time.Second), func(async.Void) {
fmt.Printf("Start 100 ms timeout\n")
async.BindIO(timeout.Timeout(100*time.Millisecond), func(async.Void) {
fmt.Printf("timeout\n")
})
})

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)
}
},
})
}
})
}

91
x/async/async_go.go Normal file
View File

@@ -0,0 +1,91 @@
//go:build !llgo
// +build !llgo
/*
* Copyright (c) 2024 The GoPlus Authors (goplus.org). All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package async
import "sync"
func BindIO[T any](call IO[T], callback func(T)) {
callback(Await(call))
}
func Await[T1 any](call IO[T1]) (ret T1) {
ch := make(chan struct{})
f := call(&AsyncContext{
Executor: Exec(),
complete: func() {
close(ch)
},
})
<-ch
return f()
}
// -----------------------------------------------------------------------------
func Race[T1 any](calls ...IO[T1]) IO[T1] {
return Async(func(resolve func(T1)) {
ch := make(chan int, len(calls))
futures := make([]Future[T1], len(calls))
for i, call := range calls {
i := i
call := call
go func() {
f := call(&AsyncContext{
Executor: Exec(),
complete: func() {
defer func() {
_ = recover()
}()
ch <- i
},
})
futures[i] = f
}()
}
i := <-ch
close(ch)
resolve(futures[i]())
})
}
func All[T1 any](calls ...IO[T1]) IO[[]T1] {
return Async(func(resolve func([]T1)) {
n := len(calls)
results := make([]T1, n)
futures := make([]Future[T1], n)
wg := sync.WaitGroup{}
wg.Add(n)
for i, call := range calls {
i := i
f := call(&AsyncContext{
Executor: Exec(),
complete: func() {
wg.Done()
},
})
futures[i] = f
}
wg.Wait()
for i, f := range futures {
results[i] = f()
}
resolve(results)
})
}

113
x/async/async_llgo.go Normal file
View File

@@ -0,0 +1,113 @@
//go:build llgo
// +build llgo
/*
* Copyright (c) 2024 The GoPlus Authors (goplus.org). All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package async
import (
"sync/atomic"
"unsafe"
"github.com/goplus/llgo/c/libuv"
)
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()
})
done := atomic.Bool{}
ctx := &AsyncContext{
Executor: Exec(),
complete: func() {
done.Store(true)
a.Async.Send()
},
}
f := call(ctx)
called := false
a.cb = func() {
if called {
return
}
a.Async.Close(nil)
result := f()
callback(result)
}
// don't delay the callback if the future is already done
if done.Load() {
called = true
a.cb()
}
}
func Await[T1 any](call IO[T1]) (ret T1) {
BindIO(call, func(v T1) {
ret = v
})
return
}
// -----------------------------------------------------------------------------
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{
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{
Executor: Exec(),
complete: func() {
results[i] = f()
done++
if done == n {
resolve(results)
}
},
})
}
})
}

33
x/async/executor_go.go Normal file
View File

@@ -0,0 +1,33 @@
//go:build !llgo
// +build !llgo
/*
* Copyright (c) 2024 The GoPlus Authors (goplus.org). All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package async
var exec = &Executor{}
type Executor struct {
}
func Exec() *Executor {
return exec
}
func Run(fn func()) {
fn()
}

View File

@@ -1,3 +1,6 @@
//go:build llgo
// +build llgo
/*
* Copyright (c) 2024 The GoPlus Authors (goplus.org). All rights reserved.
*
@@ -56,4 +59,5 @@ func Run(fn func()) {
fn()
exec.Run()
loop.Close()
setExec(nil)
}

View File

@@ -0,0 +1,35 @@
//go:build !llgo
// +build !llgo
/*
* Copyright (c) 2024 The GoPlus Authors (goplus.org). All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package timeout
import (
"time"
"github.com/goplus/llgo/x/async"
)
func Timeout(d time.Duration) async.IO[async.Void] {
return async.Async(func(resolve func(async.Void)) {
go func() {
time.Sleep(d)
resolve(async.Void{})
}()
})
}

View File

@@ -0,0 +1,44 @@
//go:build llgo
// +build llgo
/*
* Copyright (c) 2024 The GoPlus Authors (goplus.org). All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package timeout
import (
"time"
"github.com/goplus/llgo/c/libuv"
"github.com/goplus/llgo/x/async"
"github.com/goplus/llgo/x/cbind"
)
func Timeout(d time.Duration) async.IO[async.Void] {
return async.Async(func(resolve func(async.Void)) {
t, _ := cbind.Bind[libuv.Timer](func() {
resolve(async.Void{})
})
r := libuv.InitTimer(async.Exec().L, t)
if r != 0 {
panic("InitTimer failed")
}
r = t.Start(cbind.Callback[libuv.Timer], uint64(d/time.Millisecond), 0)
if r != 0 {
panic("Start failed")
}
})
}