Skip to content

Commit 07d23c9

Browse files
eliasnauraykevl
authored andcommitted
runtime: implement newcoro, coroswitch to support package iter
1 parent d5f1953 commit 07d23c9

File tree

3 files changed

+59
-3
lines changed

3 files changed

+59
-3
lines changed

src/runtime/coro.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package runtime
2+
3+
// A naive implementation of coroutines that supports
4+
// package iter.
5+
6+
type coro struct {
7+
f func(*coro)
8+
ch chan struct{}
9+
}
10+
11+
//go:linkname newcoro
12+
13+
func newcoro(f func(*coro)) *coro {
14+
c := &coro{
15+
ch: make(chan struct{}),
16+
f: f,
17+
}
18+
go func() {
19+
defer close(c.ch)
20+
<-c.ch
21+
f(c)
22+
}()
23+
return c
24+
}
25+
26+
//go:linkname coroswitch
27+
28+
func coroswitch(c *coro) {
29+
c.ch <- struct{}{}
30+
<-c.ch
31+
}

testdata/go1.23/main.go

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,29 @@
11
package main
22

3+
import "iter"
4+
35
func main() {
46
testFuncRange(counter)
7+
testIterPull(counter)
8+
println("go1.23 has lift-off!")
59
}
610

7-
func testFuncRange(f func(yield func(int) bool)) {
8-
for i := range f {
11+
func testFuncRange(it iter.Seq[int]) {
12+
for i := range it {
13+
println(i)
14+
}
15+
}
16+
17+
func testIterPull(it iter.Seq[int]) {
18+
next, stop := iter.Pull(it)
19+
defer stop()
20+
for {
21+
i, ok := next()
22+
if !ok {
23+
break
24+
}
925
println(i)
1026
}
11-
println("go1.23 has lift-off!")
1227
}
1328

1429
func counter(yield func(int) bool) {

testdata/go1.23/out.txt

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,14 @@
88
3
99
2
1010
1
11+
10
12+
9
13+
8
14+
7
15+
6
16+
5
17+
4
18+
3
19+
2
20+
1
1121
go1.23 has lift-off!

0 commit comments

Comments
 (0)