mirror of
https://github.com/tinygo-org/tinygo.git
synced 2026-08-18 11:33:59 +00:00
runtime: implement newcoro, coroswitch to support package iter
This commit is contained in:
@@ -0,0 +1,31 @@
|
|||||||
|
package runtime
|
||||||
|
|
||||||
|
// A naive implementation of coroutines that supports
|
||||||
|
// package iter.
|
||||||
|
|
||||||
|
type coro struct {
|
||||||
|
f func(*coro)
|
||||||
|
ch chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
//go:linkname newcoro
|
||||||
|
|
||||||
|
func newcoro(f func(*coro)) *coro {
|
||||||
|
c := &coro{
|
||||||
|
ch: make(chan struct{}),
|
||||||
|
f: f,
|
||||||
|
}
|
||||||
|
go func() {
|
||||||
|
defer close(c.ch)
|
||||||
|
<-c.ch
|
||||||
|
f(c)
|
||||||
|
}()
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
//go:linkname coroswitch
|
||||||
|
|
||||||
|
func coroswitch(c *coro) {
|
||||||
|
c.ch <- struct{}{}
|
||||||
|
<-c.ch
|
||||||
|
}
|
||||||
Vendored
+18
-3
@@ -1,14 +1,29 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
|
import "iter"
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
testFuncRange(counter)
|
testFuncRange(counter)
|
||||||
|
testIterPull(counter)
|
||||||
|
println("go1.23 has lift-off!")
|
||||||
}
|
}
|
||||||
|
|
||||||
func testFuncRange(f func(yield func(int) bool)) {
|
func testFuncRange(it iter.Seq[int]) {
|
||||||
for i := range f {
|
for i := range it {
|
||||||
|
println(i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func testIterPull(it iter.Seq[int]) {
|
||||||
|
next, stop := iter.Pull(it)
|
||||||
|
defer stop()
|
||||||
|
for {
|
||||||
|
i, ok := next()
|
||||||
|
if !ok {
|
||||||
|
break
|
||||||
|
}
|
||||||
println(i)
|
println(i)
|
||||||
}
|
}
|
||||||
println("go1.23 has lift-off!")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func counter(yield func(int) bool) {
|
func counter(yield func(int) bool) {
|
||||||
|
|||||||
Vendored
+10
@@ -8,4 +8,14 @@
|
|||||||
3
|
3
|
||||||
2
|
2
|
||||||
1
|
1
|
||||||
|
10
|
||||||
|
9
|
||||||
|
8
|
||||||
|
7
|
||||||
|
6
|
||||||
|
5
|
||||||
|
4
|
||||||
|
3
|
||||||
|
2
|
||||||
|
1
|
||||||
go1.23 has lift-off!
|
go1.23 has lift-off!
|
||||||
|
|||||||
Reference in New Issue
Block a user