async.Run/Await/Race/All

This commit is contained in:
Li Jie
2024-09-03 15:58:34 +08:00
parent 3c588e67b8
commit d4a72bf661
6 changed files with 557 additions and 123 deletions

View File

@@ -0,0 +1,139 @@
package main
import (
"fmt"
"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"
)
func ReadFile(fileName string) async.IO[tuple.Tuple2[[]byte, error]] {
return async.Async(func(resolve func(tuple.Tuple2[[]byte, error])) {
go func() {
bytes, err := os.ReadFile(fileName)
resolve(tuple.T2(bytes, err))
}()
})
}
func WriteFile(fileName string, content []byte) async.IO[error] {
return async.Async(func(resolve func(error)) {
go func() {
err := os.WriteFile(fileName, content, 0644)
resolve(err)
}()
})
}
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()))
resolve(i)
}()
})
}
func main() {
RunIO()
RunAllAndRace()
RunTimeout()
RunSocket()
}
func RunIO() {
async.Run(func() {
content, err := async.Await(ReadFile("1.txt")).Get()
if err != nil {
fmt.Printf("read err: %v\n", err)
return
}
fmt.Printf("read content: %s\n", content)
err = async.Await(WriteFile("2.txt", content))
if err != nil {
fmt.Printf("write err: %v\n", err)
return
}
fmt.Printf("write done\n")
})
// Translated to in Go+:
async.Run(func() {
async.BindIO(ReadFile("1.txt"), func(v tuple.Tuple2[[]byte, error]) {
content, err := v.Get()
if err != nil {
fmt.Printf("read err: %v\n", err)
return
}
fmt.Printf("read content: %s\n", content)
async.BindIO(WriteFile("2.txt", content), func(v error) {
err = v
if err != nil {
fmt.Printf("write err: %v\n", err)
return
}
fmt.Printf("write done\n")
})
})
})
}
func RunAllAndRace() {
async.Run(func() {
all := async.All(sleep(1, time.Second), sleep(2, time.Second*2), sleep(3, time.Second*3))
async.BindIO(all, func(v []int) {
fmt.Printf("All: %v\n", v)
})
})
async.Run(func() {
first := async.Race(sleep(1, time.Second), sleep(2, time.Second*2), sleep(3, time.Second*3))
v := async.Await(first)
fmt.Printf("Race: %v\n", v)
})
// Translated to in Go+:
async.Run(func() {
all := async.All(sleep(1, time.Second), sleep(2, time.Second*2), sleep(3, time.Second*3))
async.BindIO(all, func(v []int) {
fmt.Printf("All: %v\n", v)
})
})
async.Run(func() {
first := async.Race(sleep(1, time.Second), sleep(2, time.Second*2), sleep(3, time.Second*3))
async.BindIO(first, func(v int) {
fmt.Printf("Race: %v\n", v)
})
})
}
func RunTimeout() {
async.Run(func() {
fmt.Printf("Start 1 second timeout\n")
async.Await(timeout.Timeout(1 * time.Second))
fmt.Printf("timeout\n")
})
// Translated to in Go+:
async.Run(func() {
fmt.Printf("Start 1 second timeout\n")
async.BindIO(timeout.Timeout(1*time.Second), func(async.Void) {
fmt.Printf("timeout\n")
})
})
}
func RunSocket() {
// async.Run(func() {
// tcp := io.NewTcp()
// tcp.
// })
}

145
x/async/async.go Normal file
View File

@@ -0,0 +1,145 @@
/*
* 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 (
"context"
"unsafe"
_ "unsafe"
"github.com/goplus/llgo/c/libuv"
)
type Void = [0]byte
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 {
context.Context
*Executor
Complete func()
}
func Async[T any](fn func(resolve func(T))) IO[T] {
return func(ctx *AsyncContext) Future[T] {
var result T
var done bool
fn(func(t T) {
result = t
done = true
ctx.Complete()
})
return func() T {
if !done {
panic("AsyncIO: 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)
}
},
})
}
})
}

59
x/async/executor.go Normal file
View File

@@ -0,0 +1,59 @@
/*
* 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 (
"unsafe"
"github.com/goplus/llgo/c/libuv"
"github.com/goplus/llgo/c/pthread"
)
var execKey pthread.Key
func init() {
execKey.Create(nil)
}
type Executor struct {
L *libuv.Loop
}
func Exec() *Executor {
v := execKey.Get()
if v == nil {
panic("async.Exec: no executor")
}
return (*Executor)(v)
}
func setExec(e *Executor) {
execKey.Set(unsafe.Pointer(e))
}
func (e *Executor) Run() {
e.L.Run(libuv.RUN_DEFAULT)
}
func Run(fn func()) {
loop := libuv.LoopNew()
exec := &Executor{loop}
setExec(exec)
fn()
exec.Run()
loop.Close()
}