Skip to content

Commit

Permalink
runtime: implement newcoro, coroswitch to support package iter
Browse files Browse the repository at this point in the history
  • Loading branch information
eliasnaur authored and aykevl committed Oct 18, 2024
1 parent d5f1953 commit 07d23c9
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 3 deletions.
31 changes: 31 additions & 0 deletions src/runtime/coro.go
Original file line number Diff line number Diff line change
@@ -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
}
21 changes: 18 additions & 3 deletions testdata/go1.23/main.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,29 @@
package main

import "iter"

func main() {
testFuncRange(counter)
testIterPull(counter)
println("go1.23 has lift-off!")
}

func testFuncRange(f func(yield func(int) bool)) {
for i := range f {
func testFuncRange(it iter.Seq[int]) {
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("go1.23 has lift-off!")
}

func counter(yield func(int) bool) {
Expand Down
10 changes: 10 additions & 0 deletions testdata/go1.23/out.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,14 @@
3
2
1
10
9
8
7
6
5
4
3
2
1
go1.23 has lift-off!

0 comments on commit 07d23c9

Please sign in to comment.